Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

8.2 Architecture-Specific Initialization Function (setup_arch)

Following the early initialization of the security module, the start_kernel() function invokes setup_arch() to handle low-level operations specific to the underlying hardware architecture. The setup_arch() function processes the bootloader-supplied (e.g., U-BOOT) command line arguments string command_line to configure architecture-dependent peripherals, such as tuning the UART transmission baud rate. Because this function interfaces directly with the raw silicon layer, its internal program logic is completely distinct across different CPU families. When bringing up an entirely new CPU architecture, software engineers must develop this initialization suite from scratch. For the ARM architecture, the function is maintained within the architecture-specific source module linux/arch/arm/kernel/setup.c and is structured as follows:

void __init setup_arch(char **cmdline_p)
{
   const struct machine_desc *mdesc;
   setup_processor();
   mdesc = setup_machine_fdt(__atags_pointer);
   if (!mdesc)
       mdesc = setup_machine_tags(__atags_pointer, __machine_arch_type);
   if (!mdesc) {
       early_print("\nError: invalid dtb and unrecognized/unsupported machine ID\n");
       early_print("  r1=0x%08x, r2=0x%08x\n", __machine_arch_type,
           __atags_pointer);
       if (__atags_pointer)
           early_print("  r2[]=%*ph\n", 16, phys_to_virt(__atags_pointer));
       dump_machine_table();
   }
   machine_desc = mdesc;
   machine_name = mdesc->name;
   dump_stack_set_arch_desc("%s", mdesc->name);
   if (mdesc->reboot_mode != REBOOT_HARD)
       reboot_mode = mdesc->reboot_mode;
   init_mm.start_code = (unsigned long) _text;
   init_mm.end_code   = (unsigned long) _etext;
   init_mm.end_data   = (unsigned long) _edata;
   init_mm.brk        = (unsigned long) _end;
   strlcpy(cmd_line, boot_command_line, COMMAND_LINE_SIZE);
   *cmdline_p = cmd_line;
   early_fixmap_init();
   early_ioremap_init();
   parse_early_param();
#ifdef CONFIG_MMU
   early_mm_init(mdesc);
#endif
   setup_dma_zone(mdesc);
   xen_early_init();
   efi_init();
   adjust_lowmem_bounds();
   arm_memblock_init(mdesc);
   adjust_lowmem_bounds();
   early_ioremap_reset();
   paging_init(mdesc);
   request_standard_resources(mdesc);
   if (mdesc->restart)
       arm_pm_restart = mdesc->restart;
   unflatten_device_tree();
   arm_dt_init_cpu_maps();
   psci_dt_init();
#ifdef CONFIG_SMP
   if (is_smp()) {
       if (!mdesc->smp_init || !mdesc->smp_init()) {
           if (psci_smp_available())
               smp_set_ops(&psci_smp_ops);
           else if (mdesc->smp)
               smp_set_ops(mdesc->smp);
       }
      smp_init_cpus();
      smp_build_mpidr_hash();
   }
#endif
   if (!is_smp())
       hyp_mode_check();
   reserve_crashkernel();
#ifdef CONFIG_GENERIC_IRQ_MULTI_HANDLER
   handle_arch_irq = mdesc->handle_irq;
#endif
#ifdef CONFIG_VT
#if defined(CONFIG_VGA_CONSOLE)
   conswitchp = &vga_con;
#endif
#endif
  if (mdesc->init_early)
      mdesc->init_early();
}

The subsequent sections comprehensively detail the initialization mechanics and internal workflows executed across each underlying component within this architecture configuration routine.

8.2.1 Processor Architecture Setup

Processor architecture setup is initialized by invoking the setup_processor() function. This function first extracts the hardware CPU ID signature from the CP15 coprocessor space via the following macro definition block:

#define read_cpuid(reg) \
    ({ \
        unsigned int __val; \
        asm("mrc    p15, 0, %0, c0, c0, " __stringify(reg) \
            : "=r" (__val) \
            : \
            : "cc"); \
        __val; \
    })

Following this hardware register read, it calls lookup_processor() to scan the contiguous memory section bounded between the linker symbols __proc_info_begin and __proc_info_end to resolve the physical address hosting the processor descriptor structure struct proc_info_list. The binary layout and entries grouped within this link section are generated statically at link time based on the active platform target source files. The lookup_processor() wrapper routine references the underlying assembly function lookup_processor_type(), which is defined inside the architecture common assembly module linux/arch/arm/kernel/head-common.S as follows:

ENTRY(lookup_processor_type)
    stmfd    sp!, {r4 - r6, r9, lr}
    mov    r9, r0
    bl    __lookup_processor_type
    mov    r0, r5
    ldmfd    sp!, {r4 - r6, r9, pc}
ENDPROC(lookup_processor_type)

The underlying assembly loop __lookup_processor_type invoked here is the exact same routine previously executed during the low-level CPU mode initialization phase.

The proc_info_list descriptor resolved during this table scan is structured with the following fields:

struct proc_info_list {
   unsigned int             cpu_val;
   unsigned int             cpu_mask;
   unsigned long            __cpu_mm_mmu_flags;    	/* used by head.S */
   unsigned long            __cpu_io_mmu_flags;    	/* used by head.S */
   unsigned long            __cpu_flush;        	/* used by head.S */
   const char               *arch_name;
   const char               *elf_name;
   unsigned int             elf_hwcap;
   const char               *cpu_name;
   struct processor         *proc;
   struct cpu_tlb_fns       *tlb;
   struct cpu_user_fns      *user;
   struct cpu_cache_fns     *cache;
};

The proc_info_list structure aggregates vital system metadata required for central processor provisioning, including the Memory Management Unit (MMU) operational attributes, memory-mapped I/O (MMIO) attributes, compile-time target architecture name strings, and specific processor designation strings. The structural pointer field .proc targets a separate interface structure containing function vectors designed to route low-level platform behaviors, including data abort exceptions, prefetch abort traps, processor core initialization, hardware validation loops, deep sleep suspension, wake-up restoration, and cold reset sequences. The .proc field maps directly to the struct processor structure, declared as follows:

struct processor {
   void (*_data_abort)(unsigned long pc);
   unsigned long (*_prefetch_abort)(unsigned long lr);
   void (*_proc_init)(void);
   void (*check_bugs)(void);
   void (*_proc_fin)(void);
   void (*reset)(unsigned long addr, bool hvc) __attribute__((noreturn));
   int (*_do_idle)(void);
   void (*dcache_clean_area)(void *addr, int size);
   void (*switch_mm)(phys_addr_t pgd_phys, struct mm_struct *mm);
#ifdef CONFIG_ARM_LPAE
   void (*set_pte_ext)(pte_t *ptep, pte_t pte);
#else
   void (*set_pte_ext)(pte_t *ptep, pte_t pte, unsigned int ext);
#endif
   unsigned int suspend_size;
   void (*do_suspend)(void *);
   void (*do_resume)(void *);
};

The .tlb field contains a reference pointer targeting the struct cpu_tlb_fns structure. This interface provides an array of platform-specific Translation Lookaside Buffer (TLB) control pointers tasked with flushing user-space and kernel-space memory address caches. The tracking layout is defined as follows:

struct cpu_tlb_fns {
   void (*flush_user_range)(unsigned long, unsigned long, struct vm_area_struct *);
   void (*flush_kern_range)(unsigned long, unsigned long);
   unsigned long tlb_flags;
};

Within this function matrix, the .flush_user_range function pointer executes page flushes restricted to user virtual memory zones, while .flush_kern_range purges internal translation entries across the core kernel memory layout.

The processor architecture exposes specialized operations to copy or clear high-memory and low-memory page layouts across user virtual address zones via the .user reference field. These functions are encapsulated within the struct cpu_user_fns structure, which is structured as follows:

struct cpu_user_fns {
   void (*cpu_clear_user_highpage)(struct page *page, unsigned long vaddr);
   void (*cpu_copy_user_highpage)(struct page *to, struct page *from,
      unsigned long vaddr, struct vm_area_struct *vma);
};

The .cpu_clear_user_highpage handler zeroes out physical memory page maps associated with high-address user zones, while the .cpu_copy_user_highpage routine replicates the page content across separate user-space high-memory coordinates.

Hardware cache maintenance operations are registered via the .cache reference pointer, routing execution down to individual cache flushing mechanisms tracked inside the struct cpu_cache_fns structure:

struct cpu_cache_fns {
   void (*flush_icache_all)(void);
   void (*flush_kern_all)(void);
   void (*flush_kern_louis)(void);
   void (*flush_user_all)(void);
   void (*flush_user_range)(unsigned long, unsigned long, unsigned int);
   void (*coherent_kern_range)(unsigned long, unsigned long);
   int  (*coherent_user_range)(unsigned long, unsigned long);
   void (*flush_kern_dcache_area)(void *, size_t);
   void (*dma_map_area)(const void *, size_t, int);
   void (*dma_unmap_area)(const void *, size_t, int);
   void (*dma_flush_range)(const void *, const void *);
} __no_randomize_layout;

The specific low-level cache control operations can be directly deduced from their symbolic function names and are omitted here for brevity.

Within Symmetric Multiprocessing (SMP) layouts, to isolate individual processing elements and minimize resource contention or cache bouncing across processing cores, the kernel reserves a dedicated, isolated data block memory area for each processor core, designed to archive core-specific execution variables (per-CPU sections). At this early juncture in the bootstrap lifecycle, secondary multi-core components have not yet completed their initial initialization passes.

However, the architecture-critical functions exposed via the .proc vectors must be executed before these secondary cores are formally initialized. Since these secondary cores lack active per-CPU storage windows at this stage, early state parameters cannot yet be written into core-specific segments.

To resolve this limitation, Linux establishes a centralized global lookup table matrix (cpu_vtable[]) to temporarily cache the processor core interface function vectors. Each logical core entry within this array initially points to an identical structure mapping. The inline routine init_proc_vtable(const struct processor *p) handles the creation of this global tracking array, declared as follows:

static inline void init_proc_vtable(const struct processor *p)
{
   unsigned int cpu = smp_processor_id();
   *cpu_vtable[cpu] = *p;
   WARN_ON_ONCE(cpu_vtable[cpu]->dcache_clean_area !=
      cpu_vtable[0]->dcache_clean_area);
   WARN_ON_ONCE(cpu_vtable[cpu]->set_pte_ext !=
       cpu_vtable[0]->set_pte_ext);
}

Upon finalizing the layout initialization of this global interface array, the setup_processor() function extracts the individual sub-system function pointers (tlb, user, cache, and elf_hwcap) exposed by the proc_info_list block and registers them inside the global variable structures cpu_tbl, cpu_user, and cpu_cache to make them globally available for downstream kernel operations.

The proc_info_list block also provides an .elf_hwcap capabilities bitmask field, which catalogues the native hardware features (such as hardware floating-point acceleration or advanced instructions support) available to applications compiled for the Executable and Linkable Format (ELF). Because different silicon revisions implement varying subsets of extensions, the kernel invokes cpuid_init_hwcaps() to perform hardware-specific capability matching and dynamically initialize these capability registers.

Following the initialization of the ELF capabilities registers, the setup_processor() routine sets the system's global default cache line eviction and mapping policy variable (cachepolicy) to match the explicit cacheability attributes passed through the __cpu_mm_mmu_flags word of the active proc_info_list.

Because cache controller microarchitectures vary significantly across different ARM generations, the function cacheid_init() interrogates the processor architecture to extract the exact hardware cache implementation profile, fully initializing the global configuration variable cacheid.

The terminal phase of the setup_processor() function coordinates the absolute initialization of the primary CPU core by invoking the cpu_init() routine. This function programs the CP15 coprocessor register TPIDRPRW (Thread ID Register, Privileged Read/Write) with the absolute base offset value designating the core's isolated per-CPU dedicated storage allocation region. Following this registration step, it fetches and calls the low-level processing initializer _proc_init() from the centralized cpu_vtable[] lookup table array to complete the core silicon-level hardware bring-up.

The structural execution pipeline tracking the setup_processor() function is mapped out in the technical flowchart below:

Figure 8-2 setup_processor() Function Flowchart

This concludes Section 8.2.1 and the complete technical translation of the processor setup subsystem.

8.2.2 Flattened Device Tree (FDT) Processing

When the system incorporates Device Tree support, the Linux kernel invokes the setup_machine_fdt() function to query and extract structural hardware platform definitions compiled within the tree. Upon completing this hardware parsing phase, it returns an authorizing pointer routing down to the specific struct machine_desc structure descriptor that maps out the baseline features of the system. The machine_desc structure is declared within the architecture-specific machine template header arch/arm/include/asm/mach/arch.h as follows:

struct machine_desc {
   unsigned int nr;                         /* Architecture numbers reference map */
   const char *name;                        /* Architecture name string */
   unsigned long atag_offset;               /* Tagged list offset (relative) */
   const char *const *dt_compat;            
/* Array of Device Tree 'compatible' strings */
   unsigned int nr_irqs;                    /* Total number of supported IRQs */
   phys_addr_t dma_zone_size;               /* Size boundary of the DMA-capable area */
   unsigned int video_start;                /* Absolute starting address of video RAM */
   unsigned int video_end;                  /* Absolute terminating address of video RAM */
   unsigned char reserve_lp0 :1;            /* Platform configuration flag for Low-Power Mode 0 */
   unsigned char reserve_lp1 :1;            /* Platform configuration flag for Low-Power Mode 1 */
   unsigned char reserve_lp2 :1;            /* Platform configuration flag for Low-Power Mode 2 */
   enum reboot_mode reboot_mode;            /* Default hardware reset action mode */
   unsigned l2c_aux_val;                    /* Level-2 Cache auxiliary control configuration word */
   unsigned l2c_aux_mask;                   /* Level-2 Cache auxiliary mask layout vector */
   void (*l2c_write_sec)(unsigned long, unsigned);
   const struct smp_operations *smp;        /* Core SMP operational callbacks framework */
   bool (*smp_init)(void);
   void (*fixup)(struct tag *, char **);
   void (*dt_fixup)(void);
   long long (*pv_fixup)(void);
   void (*reserve)(void);                   /* Core memory reservation block function pointer */
   void (*map_io)(void);                    /* Early static I/O peripheral routing table pointer */
   void (*init_early)(void);
   void (*init_irq)(void);
   void (*init_time)(void);
   void (*init_machine)(void);
   void (*init_late)(void);
   void (*handle_irq)(struct pt_regs *);
   void (*restart)(enum reboot_mode, const char *);
};

The core setup_machine_fdt() parsing handler is defined within the system architecture Device Tree framework file arch/arm/kernel/devtree.c as follows:

const struct machine_desc * __init setup_machine_fdt(unsigned int dt_phys)
{
   const struct machine_desc *mdesc, *mdesc_best = NULL;
   if (!dt_phys || !early_init_dt_verify(phys_to_virt(dt_phys)))
      return NULL;
   mdesc = of_flat_dt_match_machine(mdesc_best, arch_get_next_mach);
   if (!mdesc) {
       const char *prop;
       int size;
       unsigned long dt_root;
       early_print("\nError: unrecognized/unsupported "
           "device tree compatible list:\n[ ");
       dt_root = of_get_flat_dt_root();
       prop = of_get_flat_dt_prop(dt_root, "compatible", &size);
       while (size > 0) {
           early_print("'%s' ", prop);
           size -= strlen(prop) + 1;
           prop += strlen(prop) + 1;
       }
       early_print("]\n\n");
       dump_machine_table(); 		/* Execution freezes inside this block; does not return */
   }
   if (mdesc->dt_fixup)
       mdesc->dt_fixup();
   early_init_dt_scan_nodes();
   __machine_arch_type = mdesc->nr;
   return mdesc;
}

Within the fundamental kernel link script configuration template vmlinux.lds.S, a specific mapping directive is specified as:

.init.arch.info : {
        __arch_info_begin = .;
        *(.arch.info.init)
        __arch_info_end = .;
    }

This alignment vector instructs the link manager to collect all input code sections matching the section syntax template *(.arch.info.init) and package them sequentially in memory bounded by the tracking markers __arch_info_begin and __arch_info_end. These target code blocks populate the system registry with the hardware descriptors of every individual motherboard revision supported by the compiled kernel binary.

The setup_machine_fdt() function interrogates these static tables by performing string matching between the descriptors linked between __arch_info_begin and __arch_info_end and the array of character keys declared under the global compatible root node property of the Flattened Device Tree. This step determines if the target central processor configuration is supported by the active kernel image. The greater the volume of character keys resolved during the verification pass, the more precise the structural compatibility mapping becomes.

During the discovery loop designed to isolate the optimal system hardware definition block, the setup_machine_fdt() function initially evaluates the binary integrity of the device tree payload by executing validation checks over the FDT magic signature word, the structure block length, the memory reservation list parameters, and the total strings module boundary. Following this integrity verification pass, it redirects execution into the specialized device tree macro parser of_flat_dt_match_machine() (within the kernel source layout, structural device tree processing handlers are uniformly prefixed with the of_ identifier, indicating Open Firmware inheritance, and are predominantly maintained within the subsystem module drivers/of/fdt.c).

This scanning utility matches the board descriptor tables with the string listings stored inside the FDT's root compatible array to extract the exact machine_desc record showcasing the highest structural compatibility rating. The core source module drivers/of/dev.c exports a vast matrix of matching device tree look-up wrappers prefixed with the of_ identifier, providing clean hooks to traverse the underlying .dtb architecture to parse nodes, hardware properties, and bus parameters.

Once a compatible system definition block matching the targeted board architecture has been successfully resolved, the setup_machine_fdt() function invokes the high-level tree scanning routine early_init_dt_scan_nodes(). This master scanning loop triggers distinct sub-node traversal callbacks, specifically early_init_dt_scan_chosen(), early_init_dt_scan_root(), and early_init_dt_scan_memory(), to parse the structural options wrapped inside the /chosen and /memory top-level tree branches.

  • Chosen Node Scanning (/chosen): If a valid /chosen container node is detected and its properties expose an active bootargs variable, the parser copies the contents of this text argument string straight into the system-wide command line tracker array boot_command_line. Concurrently, if the string properties register an initialized linux,initrd-start or linux,initrd-end field, the bootloader flags the system to support a temporary RAM-disk configuration and utilizes these physical address bounds to initialize the internal variables phys_initrd_start and phys_initrd_size.

  • Root Node Scanning (/): If the scanning loop targeting the baseline root node resolves valid #address-cells and #size-cells attributes, the system dynamically sets the operational boundaries for the variables dt_root_size_cells and dt_root_addr_cells.

  • Memory Node Scanning (/memory): When the parser processes a valid /memory block branch, confirming that its device_type identifier matches the literal definition "memory" and verifying the presence of an active linux,usable-memory or standard reg layout matrix, it extracts the memory bank parameters and appends these newly discovered coordinates straight into the kernel's active physical address allocator space, tracked via the .memory array inside the global memblock data structure (memblock.memory).

The memblock infrastructure acts as the primitive, early-stage boot allocation framework responsible for physical memory management and layout parsing long before the core virtual page or slab managers are active. The kernel relies on this tracking layer to chart the architecture partitions of physical memory. The structural layout definition of the memblock descriptor is configured as follows:

struct memblock {
   bool bottom_up;        /* Flag bit directing memory allocation trajectory (low-to-high vs high-to-low) */
   phys_addr_t current_limit;       /* Absolute boundary limit restricting early memory allocations */
   struct memblock_type memory;     /* Array tracking blocks registered as usable physical RAM */
   struct memblock_type reserved;   /* Array tracking blocks fenced off as protected, reserved memory */
};

If the physical target platform lacks Device Tree functionality, the upstream U-BOOT bootloader provides the runtime initialization parameters to the guest Linux kernel using the legacy atag parameter vector list format. As detailed in the preceding assembly bootstrap chapters, the absolute physical address pointer pointing to the base of this atag array is similarly passed to the kernel via register r2.

If the scanning engine fails to find a matching hardware descriptor block corresponding to the FDT string lists, or if the hardware environment does not implement a Flattened Device Tree, the system drops back from setup_machine_fdt() to call the legacy setup alternative setup_machine_tags() to provision the system context. The setup_machine_tags() routine compares the physical architecture number identifier __machine_arch_type against the hardcoded architecture indexes registered within every available machine_desc structure linked between the compilation boundaries __arch_info_begin and __arch_info_end. When an exact numeric match is successfully resolved, it binds that specific board structure to manage the hardware configuration. Upon securing this valid descriptor block, setup_machine_tags() initializes the reference points routing down to the target tags structure.

struct tag {
   struct tag_header hdr;
   union {
       struct tag_core        core;
       struct tag_mem32       mem;
       struct tag_videotext   videotext;
       struct tag_ramdisk     ramdisk;
       struct tag_initrd      initrd;
       struct tag_serialnr    serialnr;
       struct tag_revision    revision;
       struct tag_videolfb    videolfb;
       struct tag_cmdline     cmdline;
       struct tag_acorn       acorn;
       struct tag_memclk      memclk;
   } u;
};

If the first parameter passed to setup_machine_tags() is non-null, the pointer is initialized directly with that address value. Conversely, if the first input argument evaluates to null, the routine extracts the fallback baseline tracking pointer value from the matched machine_desc board descriptor structure. After initializing this tag context pointer, the kernel caches a persistent local backup copy of the tag block and invokes the corresponding parameter-specific parsing handlers to extract and process each constituent tag structure layout sequentially.

This concludes Section 8.2.2 and the deep technical translation of the early device parameter and tree-flattening interfaces.

8.2.3 Memory Subsystem Provisioning for the Initialization Process

Upon completing the Flattened Device Tree parsing routines, the setup_arch() function provisions the primary tracking structure init_mm utilized to coordinate memory management during the initialization phase. The init_mm structure is instantiated as a static global instance of type struct mm_struct, whose structural definition is maintained within the core memory abstractions header include/linux/mm_types.h.

This master descriptor sets the baseline parameters and tracking dimensions governing the virtual address space layout during early system bring-up; within this context, the root page table assignment init_mm.pgd = swapper_pg_dir is mapped out during the initial assembly phase of the MMU configuration.

During this architectural processing stage, setup_arch() binds the following four structural memory boundaries inside the init_mm structure to align with the linker symbols exported by the compiled kernel binary image:

  • init_mm.start_code: Initialized with the absolute virtual address matching the _text symbol, marking the absolute beginning of the executable .text instruction section.

  • init_mm.end_code: Initialized with the absolute virtual address matching the _etext symbol, marking the absolute termination boundary of the .text instruction section.

  • init_mm.end_data: Initialized with the absolute virtual address matching the _edata symbol, marking the absolute termination boundary of the initialized .data section.

  • init_mm.brk: Initialized with the absolute virtual address matching the _end symbol, marking the absolute termination boundary of the zero-filled uninitialized data (.bss) section and establishing the early heap boundary.

Following the initialization of these init_mm tracking fields, the setup_arch() function duplicates the character string payload from the global boot_command_line buffer into the primary local command-line array cmd_line to freeze it for downstream argument parsing routines.

8.2.4 Initializing the Fixed Mapping Region Memory (early_fixmap_init)

The Linux kernel safeguards a dedicated segment of virtual memory known as the fixed mapping region or fixmap, which begins at FIXADDR_START and terminates at FIXADDR_END. Prior to constructing the permanent runtime page tables, this isolated address space handles immediate I/O routing or highly specialized bare-metal operations. Once the final virtual memory hierarchy is operational, this region acts as the standard high-memory map framework (kmap), exposing temporary translation windows for the core kernel to manipulate high-memory pages. For a standard 32-bit ARM memory profile, this virtual window is located between 0xFFF00000 and 0xFFFC0000. Structurally, the real production fixmap allocations open at 0xFFFEF000, with the remaining block space down to 0xFFF00000 set aside as guard pages to prevent unmapped memory out-of-bounds page faults.

To interact with this dedicated address space during the earliest stages of the bootstrap process, the system must establish an early address mapping template within the active translation tables. The function early_fixmap_init() manages this process by writing early translation properties into the level-1 descriptors. Maintained within the memory management module git/arch/arm/mm/mmu.c, this function is defined as follows:

void __init early_fixmap_init(void)
{
	pmd_t *pmd;
	BUILD_BUG_ON((__fix_to_virt(__end_of_early_ioremap_region) >> PMD_SHIFT)
		     != FIXADDR_TOP >> PMD_SHIFT);
	pmd = fixmap_pmd(FIXADDR_TOP);
	pmd_populate_kernel(&init_mm, pmd, bm_pte);
	pte_offset_fixmap = pte_offset_early_fixmap;
}

It must be explicitly noted that these temporary configurations are only active during early boot phases; once the definitive, runtime page tables are generated down the line, this entire address translation matrix is overwritten.

On ARM Linux platforms enabling 40-bit large physical address extensions (LPAE), the MMU hardware drives a 3-tier translation flow. Conversely, on standard 32-bit ARM targets, each top-level PGD entry maps directly to a single PMD element, making the structural execution equivalent to a 2-tier page table walk (as shown in Figure 6-12). In the actual source tree implementation, the PGD table array and the PMD table array share an identical memory layout block.

Figure 8-3 The Fixmap Layout Over a 2-Tier Page Table Walk

The PGD mappings are registered into the processor co-processor registers (TTBR0 and TTBR1) during the early MMU configuration phase. The matching PMD offset vector is resolved by passing the top fixed coordinate address FIXADDR_TOP (0xFFFEF000) into the helper inline function fixmap_pmd(FIXADDR_TOP). The fixmap_pmd macro tracks back to the following definition:

static inline pmd_t * __init fixmap_pmd(unsigned long addr)
{
   return pmd_off_k(addr);
}

The underlying pointer evaluation routine pmd_off_k() is defined as follows:

static inline pmd_t *pmd_off_k(unsigned long va)
{
   return pmd_offset(pud_offset(p4d_offset(pgd_offset(&init_mm,va), va), va), va);
}

The cascading p*d_offset() macros parse the virtual address string va to calculate its specific numeric index inside that layer's page table directory. Because the standard ARM32 codebase completely collapses the intermediate software layers P4D and PUD, these translation steps are flattened to return the input reference pointer untouched:

p4d_offset(ptr, address) = ptr 
pud_offset(ptr, address) = ptr

Consequently, the operational flow inside pmd_off_k() simplifies down to:

static inline pmd_t *pmd_off_k(unsigned long va)
{
   return pmd_offset(pgd_offset(&init_mm, va), va);
}

Evaluating this pointer logic yields:

pgd_offset(&init_mm, va) 
= (&init_mm)->pgd + ((va >> PGDIR_SHIFT) & (PTRS_PER_PGD - 1))
pmd_offset(pgd_offset(&init_mm, va)) 
= (&init_mm)->pgd + ((va >> PGDIR_SHIFT) & (PTRS_PER_PGD - 1)) 
   + ((va >> PMD_SHIFT) & (PTRS_PER_PMD - 1))

Applying this calculation to resolve the target PMD coordinates for the fixmap region results in:

pmd = pmd_off_k(FIXADDR_TOP) 
    = (&init_mm)->pgd + ((FIXADDR_TOP >> PGDIR_SHIFT) & (PTRS_PER_PGD - 1)) 
      + ((FIXADDR_TOP >> PMD_SHIFT) & (PTRS_PER_PMD - 1))

Under an ARM32 short-descriptor model executing a 2-tier hardware lookup, the preprocessor shift constant PGDIR_SHIFT equals 21, the macro PTRS_PER_PGD evaluates to 2048, PMD_SHIFT is fixed to 21, and the single-element directory multiplier PTRS_PER_PMD maps to 1. This scales the calculation to:

pmd = init_mm.pgd + 0x7FF

During the initial bootstrap lifecycle, the standard ARM32 processor enforces section-based memory configurations where each physical descriptor maps out a 1 MB section. However, under Linux's software page directory alignment, each software PGD entry is designed to manage a 2 MB virtual address envelope. To cleanly map this 2 MB software logic onto the actual 1 MB structural requirements of the hardware, the Linux layout packages two consecutive physical page table descriptors (2 × 1 MB) into a single software PGD element; an odd index indicates that the access loop targets the upper 1 MB segment of the allocation window.

Once the intermediate page directory pointer (pmd) is resolved, early_fixmap_init() calls pmd_populate_kernel() to write the target descriptor properties into that slot. This mapping handler is defined inside the architecture header arch/arm/include/asm/pgalloc.h as follows:

static inline void pmd_populate_kernel(struct mm_struct *mm, pmd_t *pmdp, pte_t *ptep)
{
    __pmd_populate(pmdp, __pa(ptep), _PAGE_KERNEL_TABLE);
}
static inline void __pmd_populate(pmd_t *pmdp, phys_addr_t pte, pmdval_t prot)
{
   pmdval_t pmdval = (pte + PTE_HWTABLE_OFF) | prot;
   pmdp[0] = __pmd(pmdval);
   flush_pmd_entry(pmdp);
}

The underlying __pmd_populate() routine formats the target descriptor entry value to map exactly to (pte + PTE_HWTABLE_OFF) | prot. The subsequent chapters tracking fine-grained memory configuration explain why the system must adjust this layout offset to include PTE_HWTABLE_OFF rather than assigning a basic pte | prot bit mask.

Invoking pmd_populate_kernel(&init_mm, pmd, bm_pte) updates the level-1 page directory slot as follows:

pmd[0] = (__pa(bm_pte) + PTE_HWTABLE_OFF) | _PAGE_KERNEL_TABLE

As shown by this statement, pmd_populate_kernel() writes the absolute physical base address hosting the early Page Table Entry array bm_pte alongside its core memory attribute flags directly into the target PMD entry according to the formatting rules of the level-1 page directory. It then calls flush_pmd_entry() to force the cache controllers to clean this newly modified entry to memory, making the layout update active. This structural state update is visualized below:

Figure 8-4 Page Directory Entry Layout Mapping to the Fixed Coordinate FIXADDR_TOP

Because the early bootstrap lifecycle enforces a single-tier section-level memory configuration, the primitive block management unit defaults to a 1 MB granularity. To execute fine-grained memory operations over smaller boundaries, the system introduces a specialized, early page table tracking array named bm_pte that encapsulates 512 standalone individual PTE slots. Within this 512-descriptor array, 256 entries are parsed exclusively to track software state flags for the Linux kernel, while the remaining 256 slots map directly to control bits checked by the ARM hardware. This design gives the early bootstrap framework a fine-grained translation resolution down to a standard 4 KB page limit.

As analyzed in Section 6.3.1, the binary bit alignment tracking a Short-descriptor PMD section descriptor follows this format:

Figure 8-5 Bit Alignment Specification of a Short-Descriptor PMD Entry

The configuration constant _PAGE_KERNEL_TABLE (0b000110001) defines the target Domain field index and populates the control states for bits 4 and 0 within the descriptor word.

The data cache synchronization utility flush_pmd_entry(void *pmd) is maintained within the architecture tracking header arch/arm/include/asm/tblflush.h as follows:

static inline void flush_pmd_entry(void *pmd)
{
   const unsigned int __tlb_flag = __cpu_tlb_flags;
   tlb_op(TLB_DCLEAN, "c7, c10, 1        @ flush_pmd", pmd);
   tlb_l2_op(TLB_L2CLEAN_FR, "c15, c9, 1  @ L2 flush_pmd", pmd);
   if (tlb_flag(TLB_WB))
       dsb(ishst);
}

For ARM platforms, the flush_pmd_entry() handler expands via macro definitions to execute inline assembly instructions inside the C codebase. Upon compilation, the operations tlb_op(TLB_DCLEAN, ...) and tlb_l2_op(TLB_L2CLEAN_FR, ...) generate the following machine instructions:

mov rx, pmd
    ldr rt, [rx]
    mcr p15, 0, rt, c7, c10, 1        @ Clean data cache line by virtual address (MVA)
    mcr p15, 1, rt, c15, c9, 1        @ Clean L2 unified cache line by virtual address

Where rx and rt represent temporary working registers dynamically assigned by the compiler's optimization engine. The mcr coprocessor write commands copy the register data directly into the CP15 coprocessor control slots, forcing the cache controller to instantly clean the dirty memory descriptor from the L1/L2 cache blocks back out to physical RAM.

To clarify the precise data manipulation steps executed across this fixed memory mapping initializer, its comprehensive software processing path is presented in the flowchart below:

Figure 8-6 early_fixmap_init() Functional Execution Flowchart

This concludes Section 8.2.4 and the deep architectural translation of the early fixmap subsystems.

8.2.5 Early I/O Remapping Initialization (early_ioremap_init)

As established previously, early-stage I/O operations rely on the fixed mapping (fixmap) region. For transactional use, this space is partitioned into seven contiguous segments indexed from 0 to 6. Each segment is designated as a tracking slot containing exactly 32 page table entries (PTEs). These slots store the virtual addresses allocated for active I/O peripheral configurations. By routing lookups through this fixmap framework, the kernel resolves the corresponding physical addresses of the target I/O registers. The relative index calculation for slot i is defined by the formula FIX_BTMAP_BEGIN - NR_FIX_BTMAPS * i, which evaluates to 32 * (7 - i).

The purpose of the early I/O remapping initializer early_ioremap_init() is to compute the exact virtual addresses corresponding to these relative slot configurations and archive them within the global tracking array slot_virt[]. This virtual address calculation is executed via the __fix_to_virt() preprocessor macro:

#define __fix_to_virt(x) (FIXADDR_TOP - ((x) \<\< PAGE_SHIFT))

The early_ioremap_init() function contains no architecture-specific dependencies; it calls the generic core Linux helper routine early_ioremap_setup(). Maintained within the memory module arch/arm/mm/ioremap.c, it is defined as follows:

void __init early_ioremap_init(void)
{
   early_ioremap_setup();
}

The core early_ioremap_setup() routine is implemented within the centralized memory management subsystem file mm/early_ioremap.c as follows:

void __init early_ioremap_setup(void)
{
	int i;
	for (i = 0; i < FIX_BTMAPS_SLOTS; i++)
		if (WARN_ON(prev_map[i]))
			break;
	for (i = 0; i < FIX_BTMAPS_SLOTS; i++)
		slot_virt[i] = __fix_to_virt(FIX_BTMAP_BEGIN - NR_FIX_BTMAPS * i);
}

The early I/O remapping pipeline manages its layout matrices using three centralized global tracking arrays: prev_map[], slot_virt[], and prev_size[]. Within this tracking matrix, prev_map[] stores the virtual base address of each active, in-use memory allocation, prev_size[] logs the linear size footprint of that allocation, and slot_virt[] records the starting virtual page address assigned to each individual slot. The architectural arithmetic relationship linking slot_virt[i] to its corresponding hardware slot index i is expressed as follows:

slot_virt[i] = FIXADDR_TOP - ((FIX_BTMAP_BEGIN - NR_FIX_BTMAPS*i) << PAGE_SHIFT)
             = 0xFFFEF000 – (FIX_BTMAP_END + 32 *  (7 - i) - 1) << PAGE_SHIFT
             = 0xFFFEF000 – (32 * (7 – i) << 12)

Under standard configuration templates, FIX_BTMAP_END evaluates to 1 and PAGE_SHIFT is fixed to 12 (representing a 4096-byte page size). The mapping layout and tracking dependencies linking the individual slots, page table entries, and physical memory frames are detailed in the schematic diagram below:

Figure 8-7 Structural Mapping Linking Re-mapping Slots, Page Tables, and Physical Memory Frames

8.2.6 Boot Argument Parsing

The setup_arch() function copies the command-line boot parameters to the memory pointed to by the cmd_line pointer and invokes parse_early_options() to parse them. parse_early_options() internally calls parse_args() to evaluate all arguments supplied across the command line. The first input parameter of parse_args() is a string indicating the current phase; the second is a pointer to the arguments awaiting parsing; the third points to known parameters; the fourth defines the total number of arguments to check; the fifth and sixth specify the minimum and maximum parameter layers allowed; and the final argument points to a fallback callback function tasked with handling unrecognized parameters.

The argument parsing logic relies on parse_one(param, val, "early options", NULL, 0, 0, 0, NULL, do_early_param) to process each command-line variable sequentially. Because parse_args() passes a num_params value of 0 down to parse_one(), parse_one() itself skips basic command-line tokenization. Instead, it directly triggers the execution callback do_early_options() to inspect all historical parameters defined using legacy formats bounded between the linker symbols __setup_start and __setup_end. This legacy boot configuration structure is tracked via the struct obs_kernel_param descriptor block, which is declared as follows:

struct obs_kernel_param {
   const char *str;
   int (*setup_func)(char *);
   int early;
};

If the character string referenced by the .str pointer matches the active command-line argument parsed by the system, and the .early status flag bit evaluates to a non-zero value—or if the parsed argument context contains the sub-string "console" while a registered descriptor's .str field targets "earlycon"—the engine invokes the linked callback handler .setup_func to execute the corresponding peripheral configuration. If the compiled Linux kernel image lacks a dedicated .init.setup section, the parse_early_options() function completes without processing any operations.

8.2.7 Memory Attributes within the PMD Page Table Entries

For the ARM architecture, physical memory regions and memory-mapped I/O (MMIO) registers share a single consolidated address space. Specific regions or peripheral controllers require highly distinct hardware access attributes; for instance, certain RAM blocks support multiprocessor cache coherency sharing while others remain strictly isolated, and interrupt-driven peripheral input channels must bypass data caching entirely, whereas standard system memory relies heavily on write-back caching to optimize execution speeds. Based on these characteristics, the Linux kernel groups memory spaces into several distinct categories, ensuring that segments belonging to an identical class share uniform attributes and utilize identical page table entry flags. These native memory allocation classes are defined by the following enumeration block:

enum {
   MT_DEVICE = 0,
   MT_DEVICE_NONSHARED = 1,
   MT_DEVICE_CACHED = 2,
   MT_DEVICE_WC = 3,
   MT_MEMORY_RW_NS = 4,
   MT_UNCACHED = 5,
   MT_CACHECLEAN,
   MT_MINICLEAN,
   MT_LOW_VECTORS,
   MT_HIGH_VECTORS,
   MT_MEMORY_RWX,
   MT_MEMORY_RW,
   MT_ROM,
   MT_MEMORY_RWX_NONCACHED,
   MT_MEMORY_RW_DTCM,
   MT_MEMORY_RWX_ITCM,
   MT_MEMORY_RW_SO,
   MT_MEMORY_DMA_READY,
};

These highly specialized architectural mapping classes are modeled using the following structural metadata descriptor block:

struct mem_type {
	pteval_t prot_pte;
	pteval_t prot_pte_s2;
	pmdval_t prot_l1;
	pmdval_t prot_sect;
	unsigned int domain;
};

The function early_mm_init() invokes build_mem_type_table() to evaluate the current ARM generation, hardware platform extensions, and memory constraints. It parses the values assigned to the fields of individual mem_type records to determine the exact bit configurations tracking memory cacheability, shareability, and protection flags within the page table entries. The build_mem_type_table() routine is maintained within the memory module arch/arm/mm/mmu.c. Although the programmatic code footprint is extensive, the overwhelming majority of its logic branches handle conditional evaluations to verify the ARM processor family, flag active silicon errata workarounds, and check for 40-bit Large Physical Address Extensions (LPAE).

Following the completion of build_mem_type_table(), early_mm_init() calls the fallback routine early_paging_init(). This handler functions as a dynamic runtime patcher for platforms enabling large physical address translations. On legacy processors restricted to a standard 32-bit physical address space, if the system's machine_desc board descriptor explicitly provides a platform-specific .pv_fixup hook, early_paging_init() executes that callback; otherwise, it compiles directly down to a no-operation block.

8.2.8 DMA Allocation Zones Configuration

When subsystems allocate physical memory chunks using the kernel's memory management engines, they can pass the hardware allocation flag GFP_DMA to specify low-level requirements. The function setup_dma_zone() is invoked on startup to calculate and enforce the absolute physical upper boundary address permitted when a software routine issues a GFP_DMA allocation loop.

If this function is bypassed during architecture bring-up, or if the preprocessor build flag CONFIG_ZONE_DMA is omitted during compilation, the allocation subsystem defaults to imposing no physical address bounds over DMA requests. The setup_dma_zone() function enforces these boundary parameters globally across the platform by calculating and setting the core variables arm_dma_zone_size, arm_dma_limit, and arm_dma_pfn_limit.

8.2.9 Virtual Machine Monitor Subsystem (Xen)

Xen is a hypervisor-based virtualization technology that leverages a Virtual Machine Monitor (VMM, or Hypervisor) to allow multiple decoupled guest operating systems (Guest OS) to install and execute concurrently on a single hardware platform. The foundational structural relationship bridging the underlying hardware, the hypervisor, and the individual guest instances is mapped out in the schematic diagram below:

Figure 8-8 Structural Paradigm of a Hypervisor and Guest OS Layers

Within this topology, the distinct Virtual Machines (VMs) execute unprivileged user-space applications and run within the unprivileged DomU (User Domain) region. Conversely, Dom0 (Domain 0) operates as a highly privileged management layer whose architectural responsibility is to coordinate the global Xen engine, manage hardware allocations, and orchestrate the lifecycle or execution paths of guest domains. The hypervisor layer abstracts and executes low-level core scheduling, complex virtual memory management, and x-session management tasks—operations traditionally restricted to highly privileged execution modes.

Contemporary virtualization architectures implement hypervisors using two primary design methodologies. Type 1 Hypervisors execute bare-metal, running directly over the raw hardware platform without requiring an underlying host operating system. Consequently, a Type 1 hypervisor must implement a comprehensive suite of device drivers and resource management sub-blocks that are traditionally handled by an operating system core. Conversely, Type 2 Hypervisors sit as an application layer on top of a host operating system, leveraging the host's existing driver frameworks and infrastructure instead of re-implementing them. Because this model relies on the capabilities of an underlying operating system, it introduces the concept of a Host OS. The hypervisor utilizes the host kernel's core primitives to orchestrate physical machine virtualization. The structural block diagram below illustrates a Xen environment deployment leveraging a native Host OS configuration:

Figure 8-9 Architectural Topology of Host OS-Based Xen

The Linux operating system can be deployed both as a native Host OS providing underlying hypervisor features, and as a Guest OS executing inside an isolated virtual machine window. Mainline ARM Linux kernels natively identify exactly three virtual domain operational states: XEN_NATIVE, XEN_PV_DOMAIN, and XEN_HVM_DOMAIN.

  • XEN_NATIVE: Indicates that the Linux kernel is running directly on the bare-metal hardware. Under this operational profile, the kernel entirely suppresses Xen virtualization and disables all hypervisor hooks.

  • XEN_PV_DOMAIN: Configures the kernel to run within a Paravirtualized (PV) environment. Paravirtualization represents an early virtualization technique that does not rely on hardware acceleration features. Instead, it uses software modifications to emulate core block disk interfaces, network drivers, interrupt controllers, and system timers. This model requires the guest kernel to issue specialized supervisor instructions and interact with the MMU via explicit service requests known as Hypercalls. Running a Linux subsystem under a PV architecture requires deep kernel modifications; to support PV configurations, the Linux image must embed specialized hypervisor interface logic alongside concrete Dom0 and DomU code layers. The schematic diagram below maps out the system architecture of a virtual machine deployed via PV mechanics:

Figure 8-10 Architectural Topology of PV-Based Xen

  • XEN_HVM_DOMAIN: Configures the kernel to run within a Hardware Virtual Machine (HVM) environment. Under this operational profile, Linux leverages hardware virtualization extensions built into the CPU silicon to handle hypercall routines and trap executions automatically. The primary advantage of this model is that it dramatically accelerates execution speeds and allows standard, unmodified operating system binaries to run without kernel code adjustments. While the x86 architecture has historically provided comprehensive hardware extensions to assist virtual machine monitors, the ARM architecture also integrates high-performance virtualization hardware modules as a configurable option for silicon designers.

The Linux kernel registers and tracks whether the underlying hardware platform supports Xen virtualization using a specialized global tracking instance of type struct hyper_node. The structural declaration and default fallback assignments for this tracking variable are initialized as follows:

static __initdata struct {
   const char *compat;
   const char *prefix;
   const char *version;
   bool found;
} hyper_node = { "xen,xen", "xen,xen-", NULL, false }; 

The early initialization routine xen_early_init() handles the initial setup of this subsystem. It first invokes the flattened tree traversal manager of_scan_flat_dt() to sweep across the device tree nodes and utilizes the execution callback fdt_find_hyper_node() to scan the root tree branches for a node explicitly named "hypervisor". If a valid hypervisor node block is resolved, the engine checks its compatible string array to verify if it contains the required tracking tokens "xen,xen" or "xen,xen-". Matching these string filters confirms that the platform supports a Xen environment.

Upon successfully verifying hypervisor compatibility, the fdt_find_hyper_node() callback flags the .found field inside the global hyper_node structure to true. It then parses the trailing version numbers following the "xen,xen-" string literal within the FDT configuration and combines them with the .prefix string field to write the resulting version tracking parameters directly into the .version pointer field of the hyper_node database.

Once a valid hypervisor node has been parsed and authenticated from the device tree, the xen_early_init() function initializes the global state variable xen_domain_type to XEN_HVM_DOMAIN, directing the kernel to default to hardware-assisted HVM virtualization mode.

As analyzed in the low-level assembly bootstrap chapters, the early initialization sequence inside head.S implements the branch command bl __hyp_stub_install. If the underlying platform configuration supports hardware virtualization extensions, this command executes to call the __hyp_stub_install routine. This routine programs the ARM processor's hypervisor-mode coprocessor registers, including HVBAR (Hyp Vector Base Address Register), HCPTR (Hyp Coprocessor Trap Register), HSTR (Hyp System Trap Register), HSCTLR (Hyp System Control Register), HDCR (Hyp Debug Configuration Register), and SCTLR. Within this configuration block, HVBAR registers the absolute execution entry point routing to the hypervisor's exception and interrupt handlers, while the remaining control registers regulate the execution limits and virtualization boundaries of the ARM core. The __hyp_stub_install assembly loop is maintained within the architecture source module git/arch/arm/kernel/hyp-stub.S.

Following the configuration of the global xen_domain_type state variable, xen_early_init() invokes the feature discovery function xen_setup_features() to determine the exact matrix of virtualization features supported by the host environment, archiving the resulting capabilities bitmask inside the global array xen_features[].

To achieve this, xen_setup_features() calls the low-level wrapper HYPERVISOR_xen_version(), passing the explicit hypercall identifier constant __HYPERVISOR_xen_version (index 17) directly into register r12, and fires a hardware Hypervisor Call (hvc) exception instruction [1]. This forces an execution trap into the hypervisor's HVC exception service routine, allowing the kernel to query and audit the active features exported by the virtualization engine. The HYPERVISOR_xen_version() hypercall wrapper is defined within the architecture assembly module arch/arm/xen/hypercall.S.

Finally, if the validation pass confirms that the system is running as a privileged Dom0 management instance, xen_early_init() sets the global configuration flags within xen_start_flags. If the boot arguments have omitted an explicit console terminal definition for Dom0, the routine sets the default management console to route over the virtualized hypervisor console interface device (hvc).

8.2.10 Early Extensible Firmware Interface (EFI) Initialization

As noted in Section 4.1, the EFI System Partition (ESP) is a dedicated partition on the storage medium used to host bootloader programs formatted in the EFI standard. Regardless of whether the disk layout relies on a GUID Partition Table (GPT) or a legacy Master Boot Record (MBR), a motherboard platform executing a native UEFI-compliant boot sequence must contain an operational EFI partition, which is typically mounted under the /boot or /boot/efi directory path. (Note: Unlike standard desktop systems, native UEFI-compliant booting is rarely deployed within traditional embedded systems, which instead rely predominantly on direct U-BOOT execution paths).

The Unified Extensible Firmware Interface (UEFI) standardizes the low-level software layer bridging the underlying hardware platform and motherboard firmware with the guest operating system and its companion bootstrap loaders. A platform and firmware layer adhering strictly to the UEFI specification export a vast matrix of standard protocol interfaces and foundational hooks optimized across various storage media (including CD-ROMs, DVDs, USB mass storage, SD cards, SCSI disks, and network-based PXE interfaces). These services encompass standard partition layout parsers, secure boot verification paths, boot-time initialization services (Boot Services), and persistent runtime services (Runtime Services). The platform firmware also executes an internal Boot Manager engine to orchestrate the system-wide booting pipeline.

Consequently, any operating system or bootloader engineered to comply with the UEFI specification can initiate a clean boot cycle directly on a UEFI-compatible platform by invoking these standard service calls, completely abstracting away the granular silicon-level hardware configurations of the motherboard. Furthermore, UEFI allows the operating system loader and hardware properties to be indexed inside an interactive startup menu, enabling operators to choose dynamically from multiple distinct operating system targets. These independent operating systems can safely reside across entirely separate partitions spanning heterogeneous storage mediums.

When the platform firmware's early boot service loader LoadImage() finishes reading the operating system bootloader application binary into memory, it relinquishes execution control over to that bootloader. During this architectural handover, the platform firmware passes exactly two parameter arguments down to the operating system bootloader: the platform-assigned image handle matching the current loader instance and a master pointer targeting the primary System Table (System Table Pointer). The image handle serves as a specialized, unique interface identifier provided by the platform to service that specific loader thread. The System Table Pointer targets the master data block repository tracking the operational metrics of the current platform context; this table encapsulates entry pointers routing to standard character input/output device routines, a lookup pointer matrix targeting the structural Boot Services table, a secondary pointer matrix referencing the Runtime Services table, a master system configuration index table, and specific references to an array of secondary standardized description tables. Every data block compliant with the UEFI standard must strictly initiate its structure with a standardized table header, which is defined as follows:

struct {
	u64 Signature;
	u32 Revision;
	u32 HeaderSize;
	u32 CRC32;
	u32 Reserved;
} 

The 64-bit .Signature field acts as a unique cryptographic key variable used to differentiate table classes; for example, the master System Table is hardcoded with the signature string 0x5453595320494249, the Boot Services matrix registers the identification signature 0x56524553544f4f42, and the specialized Runtime Services block is identified by the signature string 0x56524553544e5552.

The core architectural layout mapping the primary System Table is structured as follows:

struct {
	EFI_TABLE_HEADER Hdr;
	char16 *FirmwareVendor;
	u32 FirmwareRevision;
	EFI_HANDLE ConsoleInHandle;
	EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn;
	EFI_HANDLE ConsoleOutHandle;
	EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut;
	EFI_HANDLE StandardErrorHandle;
	EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *StdErr;
	EFI_RUNTIME_SERVICES *RuntimeServices;
	EFI_BOOT_SERVICES *BootServices;
	UINTN NumberOfTableEntries;
	EFI_CONFIGURATION_TABLE *ConfigurationTable;
}

The .NumberOfTableEntries parameter registers the total count of external configuration descriptors populated inside the array, while each element inside the Configuration Table adheres to the following structural format:

struct {
	EFI_GUID VendorGuid;
	void *VendorTable;
}

The early system routine efi_init() handles the initial stage-1 setup loops required to prepare the kernel context when booting from a UEFI interface. This function is maintained within the core firmware driver path git/drivers/firmware/efi/efi-init.c with the following definition:

void __init efi_init(void)
{
struct efi_memory_map_data data;
u64 efi_system_table;
/* Retrieve FDT (Flattened Device Tree) parameters and initialize memory mapping */
efi_system_table = efi_get_fdt_params(&data);
if (!efi_system_table) 
return;
/* Perform early initialization of the EFI memory map; panic on failure */
if (efi_memmap_init_early(&data) < 0) panic("Unable to map EFI memory map.\n");
/* Initialize UEFI system table and runtime services */
if (uefi_init(efi_system_table) < 0) {
	efi_memmap_unmap();
	return;
}
reserve_regions();         /* Reserve standard physical memory regions */
efi_esrt_init();           /* Initialize EFI System Resource Table (ESRT) for firmware updates */
efi_mokvar_table_init();   /* Initialize Machine Owner Key (MOK) variable table for Secure Boot */
/* Reserve the physical memory block occupied by the EFI memory map to prevent overwriting */
memblock_reserve(data.phys_map & PAGE_MASK,
	 PAGE_ALIGN(data.size + (data.phys_map & ~PAGE_MASK)));
init_screen_info();        /* Initialize screen display info (framebuffer, etc.) for early console */
#ifdef CONFIG_ARM
/* ARM architecture-specific handling: unmap early memory map */
efi_memmap_unmap();
if (cpu_state_table != EFI_INVALID_TABLE_ADDR) {
/* ... (Omitted specific status check code) */
}
#endif
}

The unified struct efi master database encapsulates global data tracking indicators, persistent system pointers, and abstract firmware service hooks, which are structured according to the following programmatic declaration:

extern struct efi {
   const efi_runtime_services_t     *runtime;               /* EFI Runtime Services Table pointer */
   unsigned int                     runtime_version;        /* Runtime services implementation version */
   unsigned int                     runtime_supported_mask;
   unsigned long                    acpi;                   /* ACPI Table absolute address (IA64 ext 0.71) */
   unsigned long                    acpi20;                 /* ACPI 2.0 Table absolute address */
   unsigned long                    smbios;                 /* SMBIOS Table address (32-bit entry point) */
   unsigned long                    smbios3;                /* SMBIOS Table address (64-bit entry point) */
   unsigned long                    esrt;                   /* EFI System Resource Table address */
   unsigned long                    tpm_log;                /* TPM2 Event Log tracking table base */
   unsigned long                    tpm_final_log;          /* TPM2 Final Event Log tracking table base */
   unsigned long                    mokvar_table;           /* Machine Owner Key (MOK) configuration table */
   efi_get_time_t                   *get_time;
   efi_set_time_t                   *set_time;
   efi_get_wakeup_time_t            *get_wakeup_time;
   efi_set_wakeup_time_t            *set_wakeup_time;
   efi_get_variable_t               *get_variable;
   efi_get_next_variable_t          *get_next_variable;
   efi_set_variable_t               *set_variable;
   efi_set_variable_t               *set_variable_nonblocking;
   
efi_query_variable_info_t        *query_variable_info;
   efi_query_variable_info_t        *query_variable_info_nonblocking;
   efi_update_capsule_t             *update_capsule;
   efi_query_capsule_caps_t         *query_capsule_caps;
   efi_get_next_high_mono_count_t   *get_next_high_mono_count;
   efi_reset_system_t               *reset_system;
   struct efi_memory_map            memmap;
   unsigned long                    flags;
};

Upon completing the device tree scanning pass, the efi_get_fdt_params() internal routine parses the FDT nodes to extract the firmware memory allocation parameters. This early structure maps out the memory map metadata as follows:

struct efi_memory_map_data {
   phys_addr_t     phys_map;        /* Absolute physical address of the EFI memory map */
   unsigned long   size;            /* Linear size byte-count of the memory allocation map */
   unsigned long   desc_version;    /* EFI memory descriptor structural version format */
   unsigned long   desc_size;       /* Byte size dimension of an individual memory descriptor */
   unsigned long   flags;           /* Operational memory trait configuration flags */
};

After validating this memory map structure, efi_init() calls efi_memmap_init_early() to instantiate temporary page table mappings over this data region within the virtual fixmap zone. This sequence maps the virtual addresses directly down to their matching physical coordinates and utilizes the resolved mappings to fully populate the internal .memmap attribute tracking cluster inside the master efi global database. The structural tracking context of the .memmap nested block is organized as follows:

struct efi_memory_map {
   phys_addr_t     phys_map;        /* Absolute physical base address of the memory allocation map */
   void            *map;            /* Local virtual base address pointing to the memory map */
   void            *map_end;        /* Virtual boundary marking the end of the memory map block */
   int             nr_map;          /* Total count of valid descriptor segments mapped in the array */
   unsigned long   desc_version;
   unsigned long   desc_size;
   unsigned long   flags;
};

As detailed in the preceding section, the platform firmware utilizes the System Table pointer to expose and pass baseline parameters to the guest operating system kernel. By mapping and analyzing the configuration metrics supplied via this device tree system table node, the kernel can safely evaluate and override default hardware initializations.

Once the early memory map translation entries are fully operational inside the fixmap architecture, the efi_init() master handler shifts execution down to invoke uefi_init() to process the primary UEFI System Table. Maintained within the specialized driver framework file drivers/firmware/efi/efi-init.c, uefi_init() initially utilizes the __early_ioremap() routing utility to construct dedicated look-up paths over the System Table virtual region inside the fixmap area.

It then calls efi_systab_check_header() to execute integrity checks validating the System Table's signature words and revision tracking version, verifying that the payload data structures match specifications supported by the running kernel tree. Following this validation loop, the routine reads the metadata tracking parameters embedded inside the FDT's system table representation to initialize the global .runtime service function pointer block inside the master efi structure, registers the active .runtime_version constant, and outputs core diagnostic strings to log the hardware vendor name and firmware platform revision parameters to the console device.

Having successfully finalized the System Table configurations, the uefi_init() routine steps forward to parse the general configuration table array, which is statically tracked via the common_tables[] variable:

static const efi_config_table_type_t common_tables[] __initconst = {
	{ ACPI_20_TABLE_GUID, &efi.acpi20, "ACPI 2.0" },
	{ ACPI_TABLE_GUID, &efi.acpi, "ACPI" },
	{ SMBIOS_TABLE_GUID, &efi.smbios, "SMBIOS" },
	{ SMBIOS3_TABLE_GUID, &efi.smbios3, "SMBIOS 3.0" },
	{ EFI_SYSTEM_RESOURCE_TABLE_GUID, &efi.esrt, "ESRT" },
	{ EFI_MEMORY_ATTRIBUTES_TABLE_GUID, &efi_mem_attr_table, 
"MEMATTR" },
	{ LINUX_EFI_RANDOM_SEED_TABLE_GUID, &efi_rng_seed, "RNG" },
	{ LINUX_EFI_TPM_EVENT_LOG_GUID, &efi.tpm_log, "TPMEventLog" },
	{ LINUX_EFI_TPM_FINAL_LOG_GUID, &efi.tpm_final_log, "TPMFinalLog" },
	{ LINUX_EFI_MEMRESERVE_TABLE_GUID, &mem_reserve, 
"MEMRESERVE" },
	{ EFI_RT_PROPERTIES_TABLE_GUID, &rt_prop, "RTPROP" },
#ifdef CONFIG_EFI_RCI2_TABLE
	{ DELLEMC_EFI_RCI2_TABLE_GUID, &rci2_table_phys },
#endif
#ifdef CONFIG_LOAD_UEFI_KEYS
	{ LINUX_EFI_MOK_VARIABLE_TABLE_GUID, &efi.mokvar_table, "MOKvar" },
#endif
	{},
};

This array encapsulates critical architecture parameters, including the Advanced Configuration and Power Interface (ACPI) matrices and the hardware entropy seed vectors used to initialize the early kernel random number generation engines. Each array element binds a unique 128-bit Global Unique Identifier (GUID) key string to its corresponding physical target table pointer address.

The uefi_init() parser handles these fields by first invoking __early_ioremap() to construct early virtual pathways mapping the table configurations inside the fixmap layout, then routes execution straight into efi_config_parse_tables() to loop across and unpack the contents of the sub-tables. If the specific GUID token (VendorGuid) matching an incoming table entry is not matched inside this global common_tables[] database but is instead matched inside the architecture-dependent table array arch_tables[], the parsing engine dynamically replaces the target reference pointer inside arch_tables[] with the new .VendorTable base pointer provided by the device tree, cleanly executing a live firmware configuration override.

Upon completing this table parsing loop, if parameters like efi_rng_seed, mem_reserve, or rt_prop contain valid address locations rather than evaluating to the initialization constant EFI_INVALID_TABLE_ADDR, it signifies that the device tree configuration has successfully supplied valid hardware entropy pools, protected memory layouts, or specialized runtime performance properties that must be applied to configure the kernel environment.

Under this condition, efi_config_parse_tables() updates the underlying memory constraints by calling early_memremap(), modifying the mapping attributes of these specific pages to match the standard memory page type FIXMAP_PAGE_NORMAL. It then maps these tables straight into the kernel's virtual addressing space via __early_ioremap(). Finally, if the initialization parameters demand that physical memory regions be permanently walled off to secure persistent firmware tracking tables, the parsing handler triggers the memblock_reserve() memory manager to flag those specific coordinates as reserved physical RAM blocks, shielding them from general kernel allocations.

If the hardware architecture executes a native UEFI boot sequence, the accompanying Flattened Device Tree must also supply the memory allocation table characteristics, which describe how the UEFI System Table, configuration matrices, and transient runtime contexts are structured inside physical RAM. An individual entry within this memory allocation map is explicitly modeled using the following structural memory descriptor block:

struct {
        u32 type;               /* Memory allocation type (e.g., usable RAM, boot code, or reserved firmware blocks) */
        u32 pad;                /* Formatting padding field */
        u64 phys_addr;          /* Physical address */
        u64 virt_addr;          /* Virtual address */
        u64 num_pages;          /* Number of pages */
        u64 attribute;          /* Memory attribute */
};

Upon completing the uefi_init() function loop, efi_init() routes execution down to invoke the reserve_regions() routine. This helper function parses the individual memory descriptor parameters supplied by the device tree's memory allocation table attributes to dynamically register and append these active firmware memory regions straight into either the usable physical RAM block array (memblock.memory) or the protected, walled-off section tracking table (memblock.reserved) deployed during the early Linux bootstrap phase.

Starting with specification version 2.3, the UEFI standard introduces native framework support to coordinate low-level firmware updates. To manage these updates cleanly, the specification defines the EFI System Resource Table (ESRT), which is organized according to the following layout:

struct efi_system_resource_table {
        u32    fw_resource_count;
        u32    fw_resource_count_max;
        u64    fw_resource_version;
        u8     entries[];
};

Within this layout, the .entries[] block acts as a contiguous array composed of the following structural v1 system resource entries:

struct efi_system_resource_entry_v1 {
        efi_guid_t    fw_class;
        u32           fw_type;
        u32           fw_version;
        u32           lowest_supported_fw_version;
        u32           capsule_flags;
        u32           last_attempt_version;
        u32           last_attempt_status;
};

The function efi_esrt_init() initially determines whether a valid System Resource Table is present in the platform context. If the platform exposes an active resource table, the routine scans across the primary memory allocation maps to resolve the matching memory descriptor matching the ESRT tracking parameters. After validating the structural integrity and physical alignment of this system resource memory descriptor, it calls early_memremap() to instantiate early translation page table entries mapping this table inside the virtual fixmap zone. Finally, it assigns the resolved virtual address of the resource table straight to the global tracking variable esrt_data and writes the absolute table size byte-count into the global variable esrt_data_size.

Furthermore, the UEFI standard formalizes cryptographic Secure Boot protocols. When a platform enforces Secure Boot parameters, the motherboard firmware restricts execution exclusively to operating system kernels and third-party hardware device drivers that carry authenticated signatures authorized by the machine owner. To execute this secure verification pipeline, Linux defines a specialized global user credential database named the MOK (Machine Owner Key) Variable Table, where individual entries are structured according to the following descriptor format:

struct efi_mokvar_table_entry {
	char name[256];    		/* Cryptographic key signature identifier name string */
	u64  data_size;    		/* Exact byte-size dimension consumed by the key payload */
	u8   data[];        	/* Raw cryptographic key binary array */
};

When a secure, cryptographically guarded hardware platform boots, the system's global table registry (common_tables[]) contains a dedicated MOKvar descriptor entry, and a matching memory tracking descriptor is populated inside the primary memory allocation maps. The efi_init() master routine invokes efi_mokvar_table_init() to audit whether Secure Boot mechanisms are active on the platform. If the verification pass confirms Secure Boot alignment, it interrogates the memory allocation maps to locate the memory descriptor tracking the base of the user credential database. Upon resolving this target descriptor, efi_mokvar_table_init() sweeps across the embedded keys to inspect their relative data size bytes and authenticate their individual structural integrity. Once validated, it maps the entire database into virtual space by constructing temporary page table entries inside the fixmap region and permanently fences off this memory zone by adding its coordinates to the global memblock.reserved tracking array.

Once the system finishes instantiating the early translation page table paths mapping every required UEFI table payload into memory, the uefi_init() routine dynamically updates the system structures to flag the physical memory blocks occupied by the primary memory allocation map itself as completely reserved physical RAM.

When a platform launches via UEFI pipelines, it can leverage an EFI-native graphic frame buffer display infrastructure. If the platform initializes an EFI display layout, the kernel intercepts the physical address range matching the linear frame buffer base coordinate (lfb_base) and explicitly registers this region as non-direct-mapped kernel memory. Fencing off this graphics window prevents the core kernel's memory management engines from mapping standard direct virtual address translation entries over the frame buffer cells. This physical baseline coordinate is archived inside the global display telemetry structure struct screen_info.

The architecture-specific global hardware description table targeting ARM systems encapsulates a default screen info configuration profile. UEFI-driven boot routines parse this table to configure and register the primary display terminal.

Low-level infrastructure utilities tasked with parsing and executing core EFI transactions—such as efi_config_parse_tables() and efi_systab_check_header()—are defined within the core firmware processing module /drivers/firmware/efi/efi.c. Concurrently, the overarching initialization functions, memory re-mapping loops, and memory reservation allocation subroutines tracking this subsystem are maintained within the source file /drivers/firmware/efi/efi-init.c. The end-to-end technical flowchart tracking the operational stages of the efi_init() function is presented in the schematic below:

Figure 8-11 efi_init() Infrastructure Configuration Flowchart

8.2.11 Core Architectural Concepts of Address Translation

8.2.11.1 Early Boot-Stage Memory Allocator (memblock)

During the early bootstrap phase of the Linux kernel, system components continuously demand physical memory spaces to complete system staging or release transient tracking arrays. However, because the final virtual page table hierarchy has not yet been built and the highly capable main page and slab management frameworks are not yet active, the kernel must rely on a primitive direct address allocation tracking mechanism known as the Memblock Allocator to coordinate its early physical address mappings. By initializing and populating the early translation page tables during this bootstrap window, the allocator establishes the mandatory prerequisites for subsequent runtime Linux memory management. This section details the process through which Linux brings up its early page table configurations.

The early boot lifecycle relies exclusively on the global memblock variable instance to track and govern physical memory partitions. The memblock allocator is instantiated as a data structure of type struct memblock, whose core layout is configured as follows:

struct memblock {
/* Flag defining the direction of early memory allocation (low-to-high vs high-to-low) */
        bool bottom_up; 
/* Enforces the absolute maximum physical ceiling address permitted for allocations */
        phys_addr_t current_limit;  
/* Sub-structure tracking all physical blocks registered as usable RAM */
        struct memblock_type memory;   
/* Sub-structure tracking all physical blocks fenced off as protected memory */
        struct memblock_type reserved; 
};

Within this layout, the .bottom_up boolean variable dictates the trajectory algorithm utilized to isolate unallocated memory pools, and .current_limit restricts the upper physical addressing boundaries. Early system memory partitions are strictly divided into usable physical RAM blocks (registered via the .memory context domain) and protected memory windows (tracked via the .reserved context domain). Both the usable and reserved memory matrices are driven by the struct memblock_type structure, configured according to the following programmatic layout:

struct memblock_type {
        unsigned long cnt;           /* Count of distinct, non-contiguous physical memory regions currently in the array */
        unsigned long max;        /* Maximum array limit threshold allowed for region tracking slots */
        phys_addr_t total_size; /* Combined linear volume of all tracked blocks inside the array measured in bytes */
/* Reference base pointer targeting the primary array of memblock region descriptors */
        struct memblock_region *regions; 
        char *name;             /* Descriptive text identification string assigned to the memory type */
};

The parameter .cnt tracks the real-time count of isolated, non-contiguous memory segments currently linked to the array, .max defines the allocation threshold bounding the array slice, and .total_size captures the total byte capacity aggregated across all active elements. The .regions pointer targets the absolute base of an allocated array composed of individual struct memblock_region descriptor records, mapping out every discrete memory block belonging to that memory category. An individual memory block region is tracked using the following structural layout:

struct memblock_region {
        phys_addr_t base;            /* Absolute starting physical address of the specific memory block */
        phys_addr_t size;            /* Linear byte-size capacity or length of the memory block region */
        enum memblock_flags flags;   /* Architectural allocation trait masks applied to the memory block */
        int nid;     /* Numerical identifier index mapping the region to its target hardware NUMA node */
};

The physical block layout and structural cross-references governing the early memblock subsystem are presented in the schematic below:

Figure 8-12 Architectural Layout of the memblock Memory Allocation Framework

The early kernel exports an array of dedicated, minimalist allocation wrappers optimized for use during the earliest phases of architecture bring-up. Upon successfully carving out a physical block pool to fulfill an allocation request, the subsystem automatically invokes the tracking handler memblock_reserve() to permanently add the target block coordinates to the global .reserved list, protecting the memory from being overwritten by subsequent allocations.

As detailed in the fields of the region structure, each distinct memory block is explicitly mapped using its base boundary address, its linear length parameter, its specific allocation flags, and its hardware NUMA Node Identification token (nid). The specific architectural characteristics tracking a region's configuration flags can be set to manage standard RAM targets, identify volatile columns supporting dynamic physical insertion, mirror high-reliability zones, or shield specific blocks from kernel direct-mapping lookups, as defined by the following bitmask enumeration:

enum memblock_flags {
        MEMBLOCK_NONE     = 0x0,    /* Standard memory allocation profile containing no specialized layout constraints */
        MEMBLOCK_HOTPLUG  = 0x1,    /* Fences off the target region as a volatile memory block supporting physical hot-plug operations */
        MEMBLOCK_MIRROR   = 0x2,    /* Identifies mirrored physical RAM blocks duplicated for fault-tolerant reliability extensions */
        MEMBLOCK_NOMAP    = 0x4,    /* Restricts the block to prevent the kernel from instantiating direct virtual translation maps over it */
};

8.2.11.2 Linux Linked Lists

Heaps, stacks, singly linked lists, doubly linked lists, circular linked lists, and queues are fundamental data structures that are extensively utilized across the entire software engineering paradigm. To streamline data tracking and optimize cross-subsystem messaging, the Linux kernel defines a comprehensive suite of native macros and inline handlers to manipulate data lists. The generic, doubly linked list operations are declared within the master framework header git/include/linux/list.h. Concurrently, highly optimized list primitives capable of executing concurrent Read-Copy-Update operations are maintained within the synchronization header git/include/linux/rculist.h, while other specialized lists are distributed across dedicated subsystem headers.

The core Linux architecture relies almost entirely on formal list abstractions to implement higher-level sequential structures; data paradigms such as software queues, stacks, and FIFO (First-In, First-Out) buffers are constructed using fundamental list manipulation macros such as list_add_tail() or list_add().

A standard kernel list is structurally anchored by a master list head and composed of multiple sequential element nodes. The structural anchor is declared using the primitive struct list_head layout, which encapsulates forward and backward tracking references:

struct list_head {
    struct list_head *next, *prev;
};

The literal variable name assigned to this list head identifier serves as the global key tracking the entire database chain, enabling kernel routines to traverse the underlying nodes from this entry point. Typically, developers invoke the initialization macro LIST_HEAD(name) to instantiate and declare an empty list anchor named name.

An individual list node encapsulates the payload metadata required by the subsystem, composed of an embedded member of type struct list_head paired with one or more operational data fields. For example, the following block maps out a standard virtual memory tracking entry:

struct static_vm {
    struct vm_struct vm;
    struct list_head list;
};

In the majority of kernel data layouts, the .list tracking field is placed at the absolute front of the custom container structure to simplify lookups and accelerate relative offset calculations. The physical tracking configurations and pointer links governing these sequential structural paradigms are illustrated in the schematics below:

Figure 8-13 Structural Representation of a Singly Linked List

Figure 8-14 Structural Representation of a Doubly Linked List

Figure 8-15 Structural Representation of a Circular Doubly Linked List

8.2.11.3 Linux I/O Virtual Memory Management

The Linux kernel tracks and coordinates the virtual address windows allocated to peripheral memory-mapped I/O (MMIO) controllers using a global linked list named static_vmlist paired with a master reference tracking pointer named vmlist. An individual node inside the static_vmlist hierarchy is instantiated as a data structure of type struct static_vm, while the global vmlist tracking pointer references an underlying struct vm_struct instance. The vm_struct descriptor block is declared within the virtual memory abstractions header as follows:

struct vm_struct {
	struct vm_struct    *next;    /* Pointer link to the subsequent vm_struct node in the chain */
	void                *addr;      /* Base virtual address of the allocated memory window */
	unsigned long       size;       /* Combined linear size footprint of the allocation in bytes */
	unsigned long       flags;      /* System configuration allocation capability flags */
	struct page         **pages;    /* Array of physical page descriptors mapping back the allocation */
	unsigned int        nr_pages;   /* Total number of physical page frames managed by the segment */
	phys_addr_t       phys_addr;  /* Absolute physical address boundary matching the I/O region */
	const void         *caller;    /* Reference tracking the invoking subsystem or device driver */
};

The matching struct static_vm container node encapsulating this database is structured as follows:

struct static_vm {
	struct vm_struct vm;    	/* Nested allocation metadata structure */
	struct list_head list;    	/* standard doubly linked tracking list pointers */
};

The structural linkage and multi-dimensional tracking layers joining static_vmlist and the global vmlist database are organized as illustrated in the schematic diagram below:

Figure 8-16 Structural Mapping of static_vmlist and vmlist Pointers Deployed in I/O Infrastructure Control

Because the .next field embedded inside the vm_struct definition explicitly references the subsequent vm_struct instance, the global vmlist tracking pointer effectively anchors and traverses the absolute head node of this structural memory chain.

The platform architecture routine iotable_init() handles the initial setup of these I/O translation layers. It first creates permanent, level-1 translation page table descriptors for the virtual address channels requested via an incoming struct map_desc array. It then utilizes the configuration metrics provided by the mapping parameters to seamlessly insert the compiled vm_struct allocation blocks into both the static_vmlist and vmlist lookup chains. The map_desc parameter layout is declared as follows:

struct map_desc {
	unsigned long virtual;      /* Intended target virtual base address of the I/O channel */
	unsigned long pfn;          /* PFN marking the boundary of the hardware I/O resource */
	unsigned long length;       /* Linear byte-size capacity or width of the mapping window */
	unsigned int  type;         /* Memory attribute classification index matching the memory type */
};

This descriptor tracks the absolute starting virtual coordinate, the hardware-mapped Page Frame Number (PFN), the total allocation length, and the specific memory caching traits matching the targeted I/O layout.

For each individual map_desc element passed to the function, iotable_init() first claims a raw memory slice from the early boot-stage allocator to hold the static_vm descriptor tracking block. Following this allocation step, it parses the metadata parameters inside map_desc to initialize the various field assignments tracking the static_vm instance. Finally, the function inserts this newly configured static_vm descriptor into the master static_vmlist doubly linked list and wires its internal .vm.next pointer fields to insert the node directly into the centralized tracking chain anchored by the global vmlist reference pointer.

8.2.11.4 Linux Resource Management Subsystem

To implement a unified framework for managing peripheral components, the Linux kernel categorizes physical hardware resources into discrete operational infrastructure classes, including MEM (Memory-mapped IO), IO (I/O Ports), REG (Registers), IRQ (Interrupt Requests), DMA (Direct Memory Access Channels), and BUS configurations. The kernel maps and monitors each individual tracking asset through the following struct resource descriptor layout:

struct resource {
        resource_size_t start;       /* Absolute physical starting address boundary of the resource */
        resource_size_t end;         /* Absolute physical terminating address boundary of the resource */
        const char *name;            /* Descriptive identification string assigned to the resource */
        unsigned long flags;         /* Bitmask tracking resource type attributes and access capabilities */
        unsigned long desc;          /* Additional system configuration description flags */
        struct resource *parent, *sibling, *child; /* Hierarchical tree management pointer links */
};

Before an individual peripheral hardware module or integrated controller driver can execute programmatic I/O transactions, it must first file a reservation request with the core resource manager to claim its intended address range.

The CPU interfaces with physical peripheral microarchitectures using one of two primary hardware access methodologies.

  • I/O Port-Mapped Architecture: The CPU drives dedicated, independent read/write control signaling lines to manage peripheral transactions. Under this setup, the address space allocated to hardware peripherals is entirely decoupled from the address window mapping system RAM, allowing overlapping numeric coordinates to coexist without conflict. This isolated peripheral boundary space is traditionally designated as I/O Ports.

  • Memory-Mapped I/O (MMIO) Architecture: The CPU shares a unified bus control signaling matrix to coordinate read/write operations for both standard system memory and peripherals. Peripherals and system RAM share a single, consolidated address plane, meaning a peripheral register address must be unique and cannot cross-allocate or collide with a physical RAM coordinate. This integrated peripheral space is designated as Peripheral Memory or I/O Memory (iomem).

To track these distinct access models, Linux instantiates two global framework tracking variables of type struct resource: iomem_resource and ioport_resource. The iomem_resource variable monitors all memory-mapped peripherals, tracking an address envelope starting from physical coordinate 0x0 up to -1 (which translates to the maximum addressable boundary 0xFFFFFF series based on the processor's word width). Concurrently, the ioport_resource tracks port-mapped assets, mapping a baseline port range from index 0 up to IO_SPACE_LIMIT.

The global core declarations and fallback boundaries for iomem_resource and ioport_resource are initialized as follows:

struct resource iomem_resource = {
	 .name  = "PCI mem",
	 .start = 0,
	 .end   = -1ULL,
	 .flags = IORESOURCE_MEM,
};
struct resource ioport_resource = {
	.name  = "PCI IO",
	.start = 0,
	.end   = IO_SPACE_LIMIT,
	.flags = IORESOURCE_IO,
};

These baseline allocations establish the maximum total address envelopes manageable across both hardware categories. Each overarching address space can be subdivided into multiple secondary sub-spaces to be distributed among various peripheral configurations. These sub-allocations can be further partitioned down to track individual registers or internal IO blocks.

By precisely wiring the structural parent (.parent), sibling (.sibling), and child (.child) reference pointer fields embedded within each descriptor, the resource allocation blocks form a strict hierarchical tree topology. Within this structure, iomem_resource and ioport_resource serve as the definitive root nodes anchoring two independent trees, as illustrated in the schematic below:

Figure 8-17 Hierarchical Tree Topology of the iomem_resource Database

When a device driver files an allocation request to claim a hardware resource range, it must initially specify which root node to target and supply the absolute starting and terminating boundary coordinates, along with appropriate type configuration bitmasks. Based on the requested physical address bounds, the core allocation function request_resource() identifies the appropriate location to insert the candidate node along the resource tree.

The insertion algorithm strictly mandates that child nodes nested beneath a common parent must be arranged in an ascending linear sequence from the first child across all subsequent sibling nodes, sorting the address blocks from lowest to highest. If the traversal loop fails to resolve a vacant slot matching the coordinates without overlapping an operational node, the kernel rejects the block allocation as an address conflict. If a valid, vacant position is secured, the engine safely hooks the new resource descriptor into the database tree. The following sequential schematics map out different structural scenarios when adding a new peripheral resource to the tree, where the newly inserted node is highlighted in red:

Figure 8-18 Structural Layout of the Tree Before and After a Standard Sub-device Allocation

Figure 8-19 Structure Layout When the New Resource Inserts Directly as a Immediate Child of the Root Node

Figure 8-20 Structural Layout When the New Resource Anchors as a Child of the Root at the Highest Address Bound

The low-level allocation routing logic executing this tracking validation pass is driven by the internal function __request_resource():

static struct resource * __request_resource(struct resource *root, struct resource *new)
{
        resource_size_t start = new->start;
        resource_size_t end = new->end;
        struct resource *tmp, **p;
        if (end < start)
            return root;
        if (start < root->start)
            return root;
        if (end > root->end)
            return root;
        p = &root->child;
        for (;;) {
            tmp = *p;
            if (!tmp || tmp->start > end) {
                new->sibling = tmp;
                *p = new;
                new->parent = root;
                return NULL;
            }
            p = &tmp->sibling;
            if (tmp->end < start)
                continue;
            return tmp;
    }
}

This management routine is defined within the core kernel subsystem module git/kernel/resource.c. If an address overlap or allocation conflict is caught during the execution loop, the function returns a pointer tracking the conflicting peripheral resource block. If the verification pass confirms the request is completely safe, the entry is linked into the tree, and the function returns a null pointer (NULL). Furthermore, the resource.c module contains an array of baseline utilities tasked with handling resource deletion (release_resource), configuration queries, and database walk loops.

8.2.12 Low-Memory and High-Memory Boundary Adjustments (adjust_lowmem_bounds)

When the absolute physical address space of system RAM approaches or scales past the linear bounds of the kernel's virtual address space, the architecture establishes the conceptual layout of High Memory (highmem) and Low Memory (lowmem). High memory refers explicitly to the physical address blocks that are not permanently covered or mapped by the kernel's early direct-mapping translation page tables. Conversely, low memory defines the physical address envelope that is directly covered by the persistent, fixed virtual page tables, enabling the kernel core to access these page frames directly without temporary translation overlays. The precise partitioning boundary separating low memory from high memory is governed by explicit hardware configurations and silicon platform constraints.

Because the early fixed page tables cannot directly reach high memory zones, any programmatic read/write loop targeting a high-memory physical frame must construct a transient virtual page map on the fly. The kernel exports a dedicated suite of access handlers to coordinate these short-lived high-memory lookups, such as the kmap_local_page() interface. For detailed architectural guidelines, developers can reference the Linux Kernel API Reference Manual.

The adjust_lowmem_bounds() routine analyzes the topological state of the system by inspecting the struct memblock and struct memblock_region arrays to systematically tune the division line separating low memory from high memory. The allocator initially evaluates all physical memory blocks registered as usable RAM that carry no specialized layout restrictions (where the allocation mask matches MEMBLOCK_NONE) to isolate the region sitting at the absolute highest physical address bound.

The algorithm then takes the absolute terminating physical address of this highest block, compares it against the kernel configuration variable vmalloc_min (under standard ARM platform layouts, vmalloc_min defaults to 0xF0000000), isolates the lesser of these two numeric words, and executes a bitwise AND operation with the bitmask mask 0xFFF00000. The resulting calculation defines the definitive lowmem/highmem division boundary. Once this threshold is calculated, the adjust_lowmem_bounds() routine writes this parameter directly into the system-wide global variable arm_low_limit.

8.2.13 Early Boot-Stage Memory Allocator Initialization (arm_memblock_init)

The arm_memblock_init() function is an architecture-specific initializer deployed across the ARM tree to protect core memory spaces used during the early bootstrap lifecycle, explicitly registering them as reserved physical RAM to prevent subsequent boot operations or template loaders from overwriting or corrupting active data. Maintained within the initialization module arch/arm/mm/init.c, this routine is structured as follows:

void __init arm_memblock_init(const struct machine_desc *mdesc)
{
	memblock_reserve(__pa(KERNEL_START), KERNEL_END - KERNEL_START);
	arm_initrd_init();
	arm_mm_memblock_reserve();
	if (mdesc->reserve)
		mdesc->reserve();
	early_init_fdt_reserve_self();
	early_init_fdt_scan_reserved_mem();
	dma_contiguous_reserve(arm_dma_limit);
	arm_memblock_steal_permitted = false;
	memblock_dump_all();
}

The underlying subroutines and allocation tracking fences operate according to the following design parameters:

  • The primary statement memblock_reserve() claims the physical memory footprint occupied by the active executable kernel binary image, copying these exact boundary coordinates straight into the .reserved tracking array of the master memblock data structure.

  • If the target platform boot parameters configure an initial RAM-disk sequence, arm_initrd_init() isolates the memory footprint staging the compressed initrd payload and flags those blocks as protected reserved RAM. The explicit layout coordinates and linear width tracking this initrd space are parsed dynamically from the device tree parameters.

  • Depending on configuration settings, the ARMv7-M microarchitecture can locate its primary exception and interrupt vector tables across either low or high memory boundaries; the arm_mm_memblock_reserve() helper function executes to isolate and protect the physical memory blocks anchoring these vector tables.

  • Because the compiled Device Tree Blob (.dtb) payload must be evaluated continuously throughout the architecture-bringup phase and routine operations, early_init_fdt_reserve_self() calculates the block footprint hosting the tree structure and registers it as permanently reserved memory.

  • Under the baseline root node of the device tree, platform specifications frequently embed a dedicated /reserved-memory container node. This block defines explicit hardware-fenced memory windows set aside for standalone peripheral controllers (such as reserving specific pools for multimedia accelerators). The routine early_init_fdt_scan_reserved_mem() loops across the device tree to parse these allocations, committing every declared block directly to the global reserved memory array.

  • The function dma_contiguous_reserve() configures and carves out one or more high-capacity, physically contiguous memory regions inside a specialized allocation framework known as the Contiguous Memory Allocator (CMA) pool to safely service peripheral DMA hardware transactions. Upon successfully pinning these blocks, the subsystem updates the tracking layer to flag the CMA pool as reserved memory. The baseline address boundaries and maximum sizes regulating this CMA allocation window can be set via the device tree's linux,cma-default property, hardcoded within the .config build template, or passed explicitly as a kernel boot argument string via the cma= command-line parameter.

Because the underlying structural processing loops executed inside arm_memblock_init() can optionally release or adjust specific tracking blocks, the global memory layout may shift during execution. Consequently, immediately after arm_memblock_init() terminates, the master setup_arch() routing loop triggers a secondary call to adjust_lowmem_bounds() to recalculate the definitive division boundary separating low memory from high memory.

8.2.14 Interface Selection for I/O Address Translation Functions

In general, the physical address space consumed by hardware I/O peripheral registers is small, and routing these controllers through standard, high-overhead virtual memory mapping functions degrades kernel execution efficiency. To optimize register access latencies, Linux implements specialized, high-speed address translation functions designed explicitly to map I/O targets. In the majority of deployment scenarios, these streamlined I/O translation macros require that the primitive page table configuration stages complete before they can safely process lookups.

The function early_ioremap_reset() executes on startup to assert the internal operational status flag after_paging_init. When the underlying _early_ioremap() routine runs to instantiate early translation page table descriptors inside the fixmap area, it checks this status flag to choose dynamically between invoking the runtime handler __late_set_fixmap() or calling the early fallback alternative __early_set_fixmap().

For the ARM architecture, the kernel branches to process the __late_set_fixmap() pathway. This handler resolves directly to the core function __set_fixmap(), which is maintained within the architecture-specific memory module arch/arm/mm/mmu.c. The __set_fixmap() routine programs the individual target page table entries (pte) by invoking the low-level assembly subroutine cpu_v7_set_pte_ext. Depending on whether the compiled kernel targets a standard 2-tier page directory configuration or leverages the 3-tier LPAE layout, the corresponding cpu_v7_set_pte_ext assembly loops are defined within the source modules arch/arm/mm/proc-v7-2level.S or arch/arm/mm/proc-v7-3level.S respectively.

8.2.15 Virtual Page Table Initialization (paging_init)

The paging_init() function stands as the primary infrastructure handler for system virtual memory configuration, tasked with establishing the definitive, production-tier page tables. To accommodate disparate hardware profiles, Linux provides both MMU-enabled and MMU-less variants of this initialization routine. The subsequent analysis details the operational mechanics and runtime architecture of the subsystem using the MMU-enabled variant as a reference design model.

As mapped out in Figure 6-9, the upper 18 bits of a level-1 page directory entry address (PGD) are composed of the highest 18 bits tracked inside the hardware Translation Table Base Register. The lowest 2 bits of the table address pointer are strictly zero-initialized, while the remaining indexing bits are derived from the highest 12 bits of the incoming virtual address. Because only these 12 virtual address bits vary across the PGD look-up index, the master PGD array encapsulates a maximum threshold of 4,096 distinct descriptor entry slots, with each slot consuming exactly 4 bytes of storage.

Concurrently, the variable index field within a level-2 page table address is composed of 8 bits derived from the middle layer of the virtual address; this geometric alignment implies that each parent level-1 PGD descriptor routes down to reference exactly 256 individual level-2 page table entries. The definitive, terminal physical address is subsequently assembled by combining the upper 20 bits extracted from the Page Table Entry (PTE) with the lower 12 offset bits of the original virtual address. Consequently, each discrete descriptor slot inside the level-2 page table controls a memory window equal to exactly 4,096 bytes, meaning a single PTE provides address mapping resolution down to a standard 4 KB page limit.

Figure 8-21 Conceptual Layout of the 2-Tier Page Table Infrastructure

The operational definitions tracking memory page attributes within the Linux core framework do not seamlessly align with the hardwired bit representations specified under the ARM hardware architecture. For instance, the Linux software layer relies heavily on tracking specific states, such as evaluating whether a page is marked as dirty (_PAGE_DIRTY) or verifying if a page has been previously read or modified by an execution thread (_PAGE_ACCESSED); however, the native ARM hardware page tables do not expose explicit bit fields to match these software flags.

To bridge this architectural discrepancy and enable the memory management subsystem to track software states while satisfying silicon validation rules, the ARM port of the Linux kernel splits its Page Table Entries into a dual-descriptor framework. Under this design, the Page Table Entry is bifurcated into two mutually dependent descriptor classes: a Linux Software PTE and a Hardware ARM PTE. The Linux Software PTE registers the abstract access states and lifecycle telemetry required by the kernel's memory management engine, and the core memory manager subsequently intercepts these software bits to dynamically compute and write the appropriate architectural page attributes into the corresponding Hardware ARM PTE block. The comprehensive layout mapping this split-descriptor page table infrastructure is illustrated in the schematic below:

Figure 8-22 Binary Layout and Split-Descriptor Infrastructure of ARM Linux Page Tables

As shown in this structural diagram, every software-defined PGD entry effectively encapsulates a dual-pointer arrangement composed of .ptr and .hwptr. Each individual pointer references a 4-byte wide memory index; the first pointer routes down to map a block of 256 Linux Software PTE entries, while the adjacent secondary pointer references the matching block of 256 Hardware ARM PTE entries. To synchronize this architecture with software directory indexing constraints, the top-level PGD lookup array is consolidated to host exactly 2,048 software elements, where each single element maps and drives a combined block of 512 total level-2 descriptors (256 software + 256 hardware).

The core paging_init() function is maintained within the system architecture memory module git/arch/arm/mm/mmu.c, structured according to the following programmatic pipeline:

void __init paging_init(const struct machine_desc *mdesc)
{
	void *zero_page;
	prepare_page_table();
	map_lowmem();
	memblock_set_current_limit(arm_lowmem_limit);
	dma_contiguous_remap();
	early_fixmap_shutdown();
	devicemaps_init(mdesc);
	kmap_init();
	tcm_init();
	top_pmd = pmd_off_k(0xffff0000);
	zero_page = early_alloc(PAGE_SIZE);
	bootmem_init();
	empty_zero_page = virt_to_page(zero_page);
	__flush_dcache_page(NULL, empty_zero_page);
    }

8.2.15.1 Clearing the Page Tables

The page table initialization routine first calls prepare_page_table() to zero out specific segments of the level-1 page tables. This function is defined as follows:

static inline void prepare_page_table(void)
{
	unsigned long addr;
	phys_addr_t end;
	for (addr = 0; addr < MODULES_VADDR; addr += PMD_SIZE)
		pmd_clear(pmd_off_k(addr));
	for ( ; addr < PAGE_OFFSET; addr += PMD_SIZE)
		pmd_clear(pmd_off_k(addr));
	end = memblock.memory.regions[0].base + memblock.memory.regions[0].size;
	if (end >= arm_lowmem_limit)
		end = arm_lowmem_limit;
	for (addr = __phys_to_virt(end); addr < VMALLOC_START; addr += PMD_SIZE)
		pmd_clear(pmd_off_k(addr));
}

As established in preceding sections, because the ARM32 Linux implementation folds its translation architecture, the PGD, PMD, P4D, and PUD directories share an identical physical table array. The pmd_clear() macro clears the PMD descriptor entry matching the specified virtual coordinate. The function of the pmd_off_k() utility is to calculate the precise descriptor index within the master kernel PMD table array.

The first two for loops in this routine completely zero out the page table descriptors allocated to track user-space virtual addresses. The subsequent loop zeroes out the entries in the PMD array that span from the physical end of the initial primary memory block region up to the baseline origin of the vmalloc window (VMALLOC_START), following which the corresponding hardware Translation Lookaside Buffers (TLBs) are completely flushed. Figure 8-23 maps out this early virtual allocation schema; the right column represents the virtual memory address space, the left side represents the corresponding physical memory framework, and the shaded regions indicate the virtual memory tracks whose underlying descriptors have been fully cleared.

Figure 8-23 Virtual Memory Regions Mapping to Cleared Page Table Entries

8.2.15.2 Low-Memory Direct Address Mapping

As previously defined, the Linux kernel segments memory into low-memory and high-memory pools. Low memory refers strictly to the physical address envelope directly reachable by the kernel via the permanent, fixed page tables. The function map_lowmem() builds permanent page table mappings for all available physical memory blocks (memblock.memory) that carry standard, unrestricted traits (MEMBLOCK_NONE). Its implementation is structured as follows:

static void __init map_lowmem(void)
{
	phys_addr_t kernel_x_start = round_down(__pa(KERNEL_START), SECTION_SIZE);
	phys_addr_t kernel_x_end = round_up(__pa(__init_end), SECTION_SIZE);
	phys_addr_t start, end;
	u64 i;
	for_each_mem_range(i, &start, &end) {
		struct map_desc map;
		if (end > arm_lowmem_limit)
			end = arm_lowmem_limit;
  		if (start >= end)
   			break;
		if (end < kernel_x_start) { 
  			map.pfn = __phys_to_pfn(start);
   			map.virtual = __phys_to_virt(start);
  			map.length = end - start;
  			map.type = MT_MEMORY_RWX;
   			create_mapping(&map);
  		} else if (start >= kernel_x_end) { 
   			map.pfn = __phys_to_pfn(start);
     		map.virtual = __phys_to_virt(start);
     		map.length = end - start;
   			map.type = MT_MEMORY_RW;
  			create_mapping(&map);
 		} else { 
    		if (start < kernel_x_start) { 
        		map.pfn = __phys_to_pfn(start);
     			map.virtual = __phys_to_virt(start);
     			map.length = kernel_x_start - start;
     			map.type = MT_MEMORY_RW;
    			create_mapping(&map);
   			}
   			map.pfn = __phys_to_pfn(kernel_x_start);
 			map.virtual = __phys_to_virt(kernel_x_start);
			map.length = kernel_x_end - kernel_x_start;
			map.type = MT_MEMORY_RWX;
			create_mapping(&map);
			if (kernel_x_end < end) { 
				map.pfn = __phys_to_pfn(kernel_x_end);
				map.virtual = __phys_to_virt(kernel_x_end);
				map.length = end - kernel_x_end;
				map.type = MT_MEMORY_RW;
				create_mapping(&map);
			}
		}
	}
}

When building these virtual maps, the map_lowmem() function evaluates a region's position relative to the executable kernel image core and branches into four separate mapping configurations.

  • Case 1: When a physical memory block resides entirely above the terminal boundaries of the kernel image (start >= kernel_x_end), it generates standard page table descriptors mapping the entire block and flags the segment as standard read-write memory (MT_MEMORY_RW).

  • Case 2: When the block sits completely below the initial starting boundaries of the kernel image (end < kernel_x_start), it constructs page descriptors mapping the whole segment and flags it as a read, write, and executable zone (MT_MEMORY_RWX).

  • Case 3: When an available memory block partially overlaps the trailing boundary of the kernel image, it splits the allocation, creating a dedicated memory map over the block space extending past the kernel image end and setting its access permissions to read-write (MT_MEMORY_RW).

  • Case 4: When the block overlaps the initial starting boundary of the kernel image, it maps out the lower address region sitting below the kernel's starting vector, flagging this isolated block as standard read-write memory.

Figure 8-24 illustrates the exact virtual address layout within the lowmem zone whose page table descriptors have been systematically configured.

Figure 8-24 Virtual Address Configurations Initialized within the Lowmem Mapping Zone

The map_lowmem() routine utilizes the iterator macro for_each_mem_range() to sweep sequentially across every memory block registered inside memblock.memory. The __phys_to_pfn() macro translates physical coordinates into page frame indexes, __phys_to_virt() computes virtual translations from physical base metrics, and the core routine create_mapping() programs the raw binary attributes inside the corresponding PMD and PTE descriptors.

Once the low-memory address mappings are completely populated inside the active translation hierarchy, the paging_init() function calls memblock_set_current_limit(). This routine simply updates the .current_limit parameter inside the global memblock allocator structure, pinning it to the exact coordinate boundary specified by arm_lowmem_limit.

8.2.15.3 Page Table Entry Initialization for DMA Memory

As detailed during the configuration of the early memblock allocator, the system calls dma_contiguous_reserve() to isolate and carve out continuous memory channels within the Contiguous Memory Allocator (CMA) pool to service high-speed DMA operations. The physical boundaries and sizes defining these isolated blocks are archived sequentially within a master global array composed of struct dma_mmu_remap records; within this array layout, the .base field tracks the starting physical boundary of the DMA segment, and .size records its linear length.

The function dma_contiguous_remap() iterates across every registered DMA memory block to compute its respective Page Frame Numbers (PFNs), its target virtual address layout, and its linear boundary length. It packs these parameters into a temporary tracking descriptor of type struct map_desc and forces the memory attribute field .type to match the specific configuration value MT_MEMORY_DMA_READY. Following this validation pass, the routine modifies the active level-1 translation structures to construct permanent page table mappings for each map_desc entry and inserts the virtual allocation blocks into both the static_vmlist and global vmlist lookup chains. During this scanning phase, the routine systematically invokes memory clear macros to zero out the existing temporary PMD and PTE descriptors that overlap the DMA zones.

The map_desc parameter layout is declared as follows:

struct map_desc {
	unsigned long virtual;
	unsigned long pfn;
	unsigned long length;
	unsigned int  type;
};

The core dma_contiguous_remap() function is maintained within the architecture memory driver module git/arch/arm/mm/dma-mapping.c, implemented as follows:

void __init dma_contiguous_remap(void)
{
	int i;
	for (i = 0; i < dma_mmu_remap_num; i++) {
		phys_addr_t start = dma_mmu_remap[i].base;
		phys_addr_t end = start + dma_mmu_remap[i].size;
		struct map_desc map;
		unsigned long addr;
		if (end > arm_lowmem_limit)
			end = arm_lowmem_limit;
		if (start >= end)
			continue;
		map.pfn = __phys_to_pfn(start);
		map.virtual = __phys_to_virt(start);
		map.length = end - start;
		map.type = MT_MEMORY_DMA_READY;
		for (addr = __phys_to_virt(start); addr < __phys_to_virt(end); addr += 
    PMD_SIZE)
			pmd_clear(pmd_off_k(addr));
		flush_tlb_kernel_range(__phys_to_virt(start), __phys_to_virt(end));
		iotable_init(&map, 1);        /* Register DMA blocks inside the unified I/O table */
	}
}

8.2.15.4 Page Table Entry Re-Configuration for the Fixmap/Kmap Regions

As detailed in preceding chapters, during the earliest stages of the bootstrap lifecycle, the virtual fixmap region functions as a transient tracking space dedicated to early I/O routing or highly specialized bare-metal operations. However, as the system transitions into full virtual page table initialization, the functional role of the fixmap area must be refactored to serve as the long-lived high-memory mapping window (kmap). The routine early_fixmap_shutdown() manages this process by completely re-mapping and updating the translation entries over this virtual window.

The function sweeps across the individual page elements tracking the fixmap architecture within the early bm_pte array. If an interrogation of a specific descriptor reveals that its memory caching attribute bitwise matches the token flag L_PTE_MT_DEV_SHARED, it constructs a new permanent level-1 page descriptor for that block, restricting the corresponding kmap virtual slot exclusively to persistent hardware I/O device access. The virtual-to-physical address translation framework governing these fixmap/kmap regions is illustrated in the schematic below:

Figure 8-25 Virtual Address Translation Paths Within the Fixed Mapping Region

The early_fixmap_shutdown() subroutine is maintained within the architecture memory mapping module git/arch/arm/mm/mmu.c, declared as follows:

static void __init early_fixmap_shutdown(void)
{
	int i;
	unsigned long va = fix_to_virt(__end_of_permanent_fixed_addresses - 1);
	pte_offset_fixmap = pte_offset_late_fixmap;
	pmd_clear(fixmap_pmd(va));
	local_flush_tlb_kernel_page(va);
	for (i = 0; i < __end_of_permanent_fixed_addresses; i++) {
		pte_t *pte;
		struct map_desc map;
		map.virtual = fix_to_virt(i);
		pte = pte_offset_early_fixmap(pmd_off_k(map.virtual), map.virtual); 
		if (pte_none(*pte) || (pte_val(*pte) & L_PTE_MT_MASK)
  != L_PTE_MT_DEV_SHARED)   
			continue;
		map.pfn = pte_pfn(*pte);
		map.type = MT_DEVICE;
		map.length = PAGE_SIZE;
		create_mapping(&map);
	}
}

8.2.15.5 Initializing Device Address Mappings (devicemaps_init)

The devicemaps_init() function initializes the page table entry contents corresponding to the device peripheral memory space. This function first calls the early_alloc() allocation utility, which relies internally on either __memblock_find_range_bottom_up() or __memblock_find_range_bottom_down() to traverse all available physical memory blocks (memblock.memory) within lowmem across all active NUMA nodes. This lookup identifies a free memory window matching the layout constraints and claims it. During this allocation sequence, the subsystem is strictly fenced off from utilizing any address space currently occupied by the resident kernel image.

Upon successfully securing this memory block, devicemaps_init() invokes early_trap_init(). This helper routine copies the system exception vector table, the initialization stubs (stub code), and the user architecture helper code routines (kuser_helper) into the newly isolated memory area. While software engineers are universally familiar with the concept of exception vector tables, stub code and user helper wrappers represent less visible core kernel paradigms outlined below:

  • Stub Code (Stubs): Certain Linux subsystems are engineered to natively support heterogeneous operational modalities or manage multi-variant hardware peripherals. Achieving this adaptability often demands dynamic runtime register or instruction modifications. Permanent, memory-resident stub code sequences act as execution anchors that can be cleanly patched or reconfigured on the fly to seamlessly redirect scheduling loops. Examples include the EFI boot stubs, systemd integration stubs, and specialized I2C controller stubs.

  • User Architecture Helpers (kuser_helper): Different generations of CPUs execute varying instruction sets. To provide user space with high-performance operations that a specific processor may lack in hardware—such as atomic compare-and-swap (CAS) loops or specialized memory barriers—and which require low-level kernel assistance to execute safely, Linux encapsulates an optimized array of user helper codes. These routines are permanently hosted within a specific virtual kernel window but are exposed with unique read-only user access permissions, allowing user-space applications to invoke them directly to bypass standard high-overhead system call (sys_call) traps.

After staging the exception vector tables and helpers inside the allocated memory block, the devicemaps_init() function zeroes out the existing level-1 page directory elements spanning the virtual memory window between the vmalloc origin (VMALLOC_START) and the top fixed coordinate address mask (FIXADDR_TOP & PMD_MASK). However, because the narrow virtual cushion located between FIXADDR_TOP and FIXADDR_TOP - PAGE_SIZE is continuously leveraged by the active early fixmaps interface, the translation entries mapping this specific sub-segment are safely preserved.

If the active build parameters enable an Execute-In-Place (CONFIG_XIP_KERNEL) image topology, the routine constructs dedicated section descriptors mapping out the virtual address window defined by the configuration constant MODULES_VADDR down to its underlying physical target CONFIG_XIP_PHYS_ADDR. Concurrently, if the architecture configuration maps a hardware cache-flushing memory column, the parser programs page table entries over the virtual address zone anchored at FLUSH_BASE (pointing to the hardwired physical coordinate FLUSH_BASE_PHYS).

Subsequently, devicemaps_init() sets up a standard level-1 descriptor targeting the absolute virtual address vector 0xFFFF0000 with a linear width equal to PAGE_SIZE; this precise memory window hosts the core exception vectors. If the kernel configuration includes support for user-space architecture helpers (CONFIG_KUSER_HELPERS), the zone's memory attribute classification index is explicitly set to MT_HIGH_VECTORS; otherwise, it falls back to match the flag MT_LOW_VECTORS.

If the hardwired system control registers dictate that the processor tracks its active exception vector base address within low memory (the ARM architecture permits toggling the exception trap entries to anchor at either base coordinate 0x00000000 or 0xFFFF0000), the function instantiates translation page table entries mapping out a 2 * PAGE_SIZE virtual window starting at address 0x00000000, classification-indexing this entire block as MT_LOW_VECTORS.

The Linux kernel also reserves a dedicated, read-only memory page classified as type MT_LOW_VECTORS located at the virtual address coordinate 0xFFFF0000 + PAGE_SIZE. The devicemaps_init() routine creates a valid translation entry for this slot to allow low-level kernel mechanisms to access structural parameters safely.

The framework also incorporates hooks to call platform-specific memory routing configurations provided directly by the silicon manufacturer. If the active machine_desc board descriptor indicates that the target motherboard exports a custom I/O memory routing function (.map_io), devicemaps_init() invokes this platform-specific callback to completely initialize the peripheral page directory mappings.

Finally, the PCI expansion bus handles high-bandwidth communications by claiming a specific, dedicated block of the platform address envelope. A 2 MB virtual window beginning at base address PCI_IO_VIRT_BASE (0xFEE00000) is explicitly set aside to map the PCI I/O address space. If the early initialization sequence has not yet reserved this memory window, the device mapping function queries the memblock.memory pool to isolate a free memory frame. It constructs a static struct static_vm tracking structure over this block, caches the target PCI I/O virtual addresses inside it, configures the structural allocation flags, and sets the software entry points for utilities interacting with the PCI I/O domain. Once validated, it links this entry into the global static_vmlist look-up chain.

The devicemaps_init() function is defined within the architecture memory driver module git/arch/arm/mm/mmu.c as follows:

static void __init devicemaps_init(const struct machine_desc *mdesc)
{
	struct map_desc map;
	unsigned long addr;
	void *vectors;
	vectors = early_alloc(PAGE_SIZE * 2);
	early_trap_init(vectors);
	for (addr = VMALLOC_START; addr < (FIXADDR_TOP & PMD_MASK); 
  addr += PMD_SIZE)
		pmd_clear(pmd_off_k(addr));
#ifdef CONFIG_XIP_KERNEL
	map.pfn = __phys_to_pfn(CONFIG_XIP_PHYS_ADDR & SECTION_MASK);
	map.virtual = MODULES_VADDR;
	map.length = ((unsigned long)_exiprom - map.virtual + ~SECTION_MASK) & SECTION_MASK;
	map.type = MT_ROM;
	create_mapping(&map);
#endif
#ifdef FLUSH_BASE
	map.pfn = __phys_to_pfn(FLUSH_BASE_PHYS);
	map.virtual = FLUSH_BASE;
	map.length = SZ_1M;
	map.type = MT_CACHECLEAN;
	create_mapping(&map);
#endif
#ifdef FLUSH_BASE_MINICACHE  
	map.pfn = __phys_to_pfn(FLUSH_BASE_PHYS + SZ_1M);
	map.virtual = FLUSH_BASE_MINICACHE;
	map.length = SZ_1M;
	map.type = MT_MINICLEAN;
	create_mapping(&map);
#endif
	map.pfn = __phys_to_pfn(virt_to_phys(vectors));
	map.virtual = 0xffff0000;
	map.length = PAGE_SIZE;
#ifdef CONFIG_KUSER_HELPERS
	map.type = MT_HIGH_VECTORS;
#else
	map.type = MT_LOW_VECTORS;
#endif
	create_mapping(&map);
	if (!vectors_high()) {
		map.virtual = 0;
		map.length = PAGE_SIZE * 2;
		map.type = MT_LOW_VECTORS;
		create_mapping(&map);
	}
	map.pfn += 1;
	map.virtual = 0xffff0000 + PAGE_SIZE;
	map.length = PAGE_SIZE;
	map.type = MT_LOW_VECTORS;
	create_mapping(&map);
	if (mdesc->map_io)
		mdesc->map_io();
	else
		debug_ll_io_init();
	fill_pmd_gaps();
	pci_reserve_io();
	local_flush_tlb_all();
	flush_cache_all();
	early_abt_enable();
}

The core kernel natively addresses system RAM through the permanent, direct-mapped fixed page tables. When the virtual address space split ratio is configured to the standard 3G/1G user/kernel layout, these fixed page tables can only directly map a maximum physical allocation window equal to approximately 896 MB of low memory. To safely read or modify physical frames residing beyond this 896 MB boundary inside high memory, the system must deploy dynamic page tables. As analyzed within the virtual memory layout profiles, the system provisions an isolated virtual memory region designated as the kmap zone; Linux utilizes this specific window to execute dynamic virtual-to-physical address mapping translations.

The master paging_init() routine calls kmap_init() to initialize these dynamic translation structures. If the active platform compilation switches enable high-memory framework capabilities (CONFIG_HIGHMEM), the kmap_init() function first checks whether the virtual address coordinate anchoring the base of the permanent kernel mapping space (PKMAP_BASE) possesses a valid level-1 descriptor inside the PMD directory. If this lookup returns an empty slot, the subsystem claims a raw memory frame from the early allocator, constructs a dedicated level-2 Page Table Entry (PTE) table array starting at PKMAP_BASE, and uses the absolute physical address of this newly generated table to update the corresponding PMD entry. By systematically re-programming the bit vectors inside these level-2 PTE descriptors at runtime, the kernel can dynamically remap the virtual memory channels extending above PKMAP_BASE to point to disparate physical frames across high memory. This dynamic translation layout is organized as illustrated in the schematic diagram below:

Figure 8-26 Structural Pipeline Governing Runtime Dynamic Address Mappings

The early initialization function tasked with configuring these dynamic lookup structures is defined as follows:

static void __init kmap_init(void)
{
#ifdef CONFIG_HIGHMEM
	pkmap_page_table = early_pte_alloc(pmd_off_k(PKMAP_BASE), PKMAP_BASE, 
	                                  _PAGE_KERNEL_TABLE); 
#endif
	early_pte_alloc(pmd_off_k(FIXADDR_START), FIXADDR_START, _PAGE_KERNEL_TABLE);
}

8.2.15.6 Tightly-Coupled Memory Initialization (tcm_init)

During memory read/write cycles, the Linux kernel relies heavily on data caches to optimize subsystem performance. However, deploying caches introduces variance into memory access latencies. During a memory read transaction, if the requested data hits the cache line, the latency is extremely low. Conversely, if a cache miss occurs, the processing controller must first fetch the cache line from physical RAM into the cache buffer before delivering it to the processing core, resulting in significantly higher latencies. A similar variance occurs during memory write operations depending on the dirty eviction and write-through policies applied by the controller.

In certain architectural domains—such as low-level interrupt handling and hard real-time thread scheduling—the kernel demands absolute, deterministic memory read/write latency. To fulfill these constraints, the ARM processor architecture integrates Tightly-Coupled Memory (TCM) as a configurable silicon element. Tightly-Coupled Memory behaves as an uncacheable, ultra-low-latency SRAM region embedded directly adjacent to the processor core logic. Execution commands and load/store strings targeting this region completely bypass the hardware cache controllers, operating directly over the localized memory bank with constant, zero-wait-state cycle timing.

The ARM Tightly-Coupled Memory framework is divided into two distinct, isolated physical sub-blocks: Instruction TCM (itcm) and Data TCM (dtcm). The physical address ranges routing down to these sub-blocks are dynamically mapped by programming internal TCM control registers. Although the processor core queries the TCM region through the MMU pipeline, the MMU frequently sits in a disabled state during real-time loops that target TCM cells. Consequently, TCM memory remapping enforces a strict 1:1 identity transformation matrix, ensuring that a virtual coordinate aligns perfectly with its true physical cell target. Within the ARM Linux source code, the itcm and dtcm virtual envelopes are systematically mapped to span the address spaces from 0xFFFE0000 to 0xFFFE7FFF and 0xFFFE8000 to 0xFFFEFFFF respectively.

Each distinct TCM sub-block can be internally partitioned to host between 0 and 4 memory banks. The explicit count of active banks provisioning the itcm and dtcm spaces can be determined by reading bits [2:0] and [18:16] of the hardware TCMTR (TCM Type Register) within the CP15 coprocessor. Modern ARM silicon architectures predominantly divide both the itcm and dtcm spaces into exactly two independent banks. This allows the system to isolate one bank exclusively to service unprivileged secure mode threads while leaving the secondary bank accessible to standard user-space environments.

The physical attributes and runtime operations of these memory banks are configured via the TCM Region Registers located inside the CP15 c9 control group. These registers allow software engineers to select whether the individual banks operate under standard user permissions or restrict access to Secure Mode vectors. Interrogating or altering these CP15 c9 registers strictly requires that the CPU core be operating within a privileged execution ring. If an unprivileged user-space application thread lacking secure cryptographic authorization attempts to read this coprocessor region, the hardware instantly triggers an Undefined Instruction exception trap.

To guarantee that the Linux bootstrap lifecycle can advance smoothly even when executing on unprovisioned target hardware where TCM access rights are blocked or unimplemented, the kernel deploys an early assembly exception trapping hook mechanism. This architecture intercepts the unhandled Undefined Instruction trap and dynamically zeroes out the destination register tracking the read attempt. Following this software repair, the mechanism increments the instruction counter and passes execution smoothly back to the bootstrap sequence, preventing an early system lockup. The structure definition and callback handler implementing this early undefined instruction trap handler are configured as follows:

#define TCM_REGION_READ_MASK       0xffff0fdf
#define TCM_REGION_READ_INSTR      0xee190f11
#define DEST_REG_SHIFT             12
#define DEST_REG_MASK              0xf
static int __init tcm_handler(struct pt_regs *regs, unsigned int instr)
{
	regs->uregs[(instr >> DEST_REG_SHIFT) & DEST_REG_MASK] = 0;    
	regs->ARM_pc += 4;     /* Advance pc past the faulting opcode: ARM_pc = uregs[15] */
	return 0;
}
static struct undef_hook tcm_hook __initdata = {
	.instr_mask    = TCM_REGION_READ_MASK,
	.instr_val     = TCM_REGION_READ_INSTR,
	.cpsr_mask     = MODE_MASK,
	.cpsr_val      = SVC_MODE,
	.fn            = tcm_handler
};

Within this exception interface framework, the incoming struct pt_regs *regs tracking structure functions as the primary register context dump that preserves the CPU core states captured at the exact moment the system exception was trapped.

Across contemporary Linux deployments, the ultra-low-latency TCM subsystem is heavily leveraged to host fast interrupt handlers (FIQ), manage CPU idle scheduling loops during external DRAM self-refresh power-saving phases, and process low-level register tuning commands required to configure or reset external multi-channel memory controller timings.

The master initialization loop invokes the tcm_init() routine to provision and format the TCM address spaces. This function is maintained within the system architecture resource module git/arch/arm/kernel/tcm.c. The routine initially verifies whether the active ARM core generation falls below the ARMv5 specification; if it targets an out-of-date ARMv4 or earlier platform, the subsystem aborts bring-up and returns immediately. If the silicon architecture implements an ARMv6-compatible TCM model, the function samples the hardware TCMTR register to resolve the exact bank distributions available to the itcm and dtcm spaces.

Upon successfully reading these bank boundaries, tcm_init() registers the early exception trap hook structure tcm_hook, appending the callback handler directly to the master undefined instruction exception tracking chain to ensure the kernel can safely trap any subsequent unprivileged register probes.

The kernel can dynamically shift the absolute physical address ranges routing down to individual memory banks by modifying the parameters inside the CP15 c9 c2 configuration slots. The tcm_init() routine manages this step by calling the internal helper utility setup_tcm_bank() to step through and register the explicit boundary boundaries for every itcm and dtcm bank block. Under standard layouts, the baseline address of the initial primary itcm bank is fixed to open at 0xFFFE0000, while the starting coordinate of the primary dtcm bank is assigned to open at 0xFFFE8000. The physical target addresses assigned to any secondary memory banks are calculated dynamically at runtime to match the linear volume of compiled machine instructions and data constants marked for TCM relocation.

Once the physical boundary boundaries are calculated for each active bank, the system establishes the precise global starting and terminating addresses defining the itcm and dtcm blocks. The routine then invokes the core memory manager utility request_resource() to formally register these hardware address blocks inside the system-wide global I/O peripheral resource database iomem_resource.

Following this reservation step, iotable_init() creates permanent level-1 translation descriptor entries mapping these TCM coordinates inside the active page tables, and attaches the corresponding vm_struct virtual allocation structures straight into the global static_vmlist and vmlist translation chains.

The final operational responsibility managed within the tcm_init() pipeline is to copy the critical real-time execution instruction sequences and persistent data tables from their temporary loading blocks inside standard system RAM (bounded by the linker symbols __sdtcm_data, __edtcm_data, and __dtcm_start) and unpack them directly into the newly active high-speed itcm and dtcm SRAM cells.

It must be explicitly noted that the overwhelming majority of commercial application processor chips do not implement tightly-coupled memory modules on chip, leaving this subsystem inactive on standard hardware platforms.

8.2.15.7 Zero Page Allocation

Within the Linux kernel architecture, the Zero Page (empty_zero_page) operates as a globally shared, specialized physical memory page whose data bytes are completely initialized to zero. It represents an optimized memory allocation mechanism designed to maximize overall system execution efficiency and reduce memory pressure.

When a user-space application thread calls dynamic memory allocators like malloc() to request massive memory blocks, or initializes an anonymous virtual memory map via the mmap() system call, the kernel optimizes resource consumption by completely bypassing immediate physical memory allocation. If the executing process merely performs read sweeps across this newly acquired but unwritten virtual space, the kernel routes all of the process's associated virtual page table lookups down to address this single physical frame—the Zero Page.

The moment the process attempts a write operation to alter a data block within that page, the MMU hardware intercepts the transaction to fire a Page Fault exception trap. The kernel's page fault handler captures the trap, dynamically allocates a fresh physical page frame from the zone allocators, replicates the zero-bytes context of the Zero Page into the new frame, and re-programs the level-2 page table entries to point directly to the newly instantiated physical memory.

The paging_init() master loop calls the early boot-stage allocator early_alloc() to claim a physical memory block equal to exactly PAGE_SIZE (typically 4096 bytes) and zero-initializes its entire payload footprint. The reference tracking pointer targeting this frame is globally exposed via the symbol empty_zero_page.

8.2.15.8 Boot-Stage Memory Initalization (bootmem_init)

The paging_init() routine invokes bootmem_init() to initialize the foundational components tracking the boot memory system. The low-level operational workflow and execution paths through which bootmem_init() manages physical memory page tracking differ strictly depending on the core memory model enabled within the compiled kernel configuration templates.

8.2.15.8.1 Architectural Classification of Linux Memory Models

To coordinate transactional memory allocations, page frame lookups, and reclamation routines, the Linux kernel relies on stylized Memory Models to map out the underlying hardware layout. The framework supports several discrete memory tracking topologies to adapt cleanly to the diverse characteristics of heterogeneous volatile and non-volatile memory layouts. Contemporary Linux kernels formally identify the Flat Memory Model (FLATMEM), the Discontiguous Memory Model (DISCONTIGMEM), the Sparse Memory Model (SPARSEMEM), and hardware Device Memory zones. The core architectural abstractions defining these memory paradigms are outlined below:

1. Flat Memory Model (FLATMEM)

The Flat Memory Model represents the most linear and mathematically direct memory management paradigm, optimized for Uniform Memory Access (UMA / non-NUMA) architectures where the physical memory banks are deployed in a continuous or mostly contiguous physical address space. Under this configuration, the kernel tracks physical memory frames sequentially through a monolithic global array of page descriptors named mem_map. Every single element slot inside this master array encapsulates an individual struct page instance mapping a specific 4 KB hardware page frame.

2. Discontiguous Memory Model (DISCONTIGMEM)

The Discontiguous Memory Model abstracts physical memory as a sequential string of non-contiguous hardware blocks or nodes, structurally resembling NUMA memory topologies. Under this paradigm, each independent physical memory chunk is partitioned into an isolated, standalone memory management subsystem maintained by a dedicated struct pglist_data node descriptor. The system-wide memory map is managed by an array of pg_data_t instances tracking the physical blocks resident within each node. Each node structure implements a .node_start_pfn tracking field to register the physical Page Frame Number (PFN) marking its initial baseline boundary. Furthermore, every individual pglist_data_t element embeds a localized .node_mem_map field—the structural equivalent of the global flatmem mem_map array—which routes down to an architecture-wide virtual tracking descriptor array named vmemmap to manage the constituent struct page descriptors for that specific memory block. (Note: In modern kernels, DISCONTIGMEM has been largely deprecated in favor of SPARSEMEM).

3. Sparse Memory Model (SPARSEMEM)

The Sparse Memory Model stands as the most flexible, modular, and performance-optimized tracking layout within the Linux kernel architecture. It represents the dominant memory model across contemporary platforms and functions as the exclusive paradigm capable of driving high-level memory hot-plug, hot-unplug, and hot-remove routines. It natively supports arbitrary physical layout mappings used by non-volatile memory devices and integrates deferred initialization mechanisms to prevent massive memory footprint allocation loops during early boot phases on hyperscale enterprise servers.

The sparse memory framework subdivides the global address space into one or more top-level tracking structures called Roots. Each individual root encapsulates a collection of localized Memory Sections (struct mem_section), which are further partitioned into standard physical memory pages. The total volume of active root instances is resolved by taking the absolute highest physical section address bound and dividing it by the constant mapping threshold bounding each root.

When the architecture build switches disable extreme sparse indexing optimization (CONFIG_SPARSEMEM_EXTREME), the system flattens its tracking layer to bundle all memory blocks under a single monolithic root container. Conversely, when SPARSEMEM_EXTREME is active, the memory matrix is dynamically segmented across a multi-dimensional array of separate root slots. For a 32-bit ARM aplicaciones processor, the structural relationship and architectural grid linking the physical address plane, the section boundaries, and the individual pages are mapped out in the schematic diagram below:

Figure 8-27 Structural Layout and Section Paging Grid of the Sparse Memory Model

An individual memory section is represented internally by a struct mem_section descriptor block. This structure implements a key operational field named section_mem_map of type unsigned long. Architecturally, section_mem_map functions as an abstract pointer routing down to an array of individual physical page frames. The precise bitwise layout tracking the parameters within the section_mem_map word is organized as illustrated in the schematic below:

Figure 8-28 Bit Alignment Encoding of the section_mem_map Field

The lower-order control bits within this encoded configuration word enforce the following operational tracking states:

  • Bit 0 (SECTION_MARKED_PRESENT): Functions as the section presence indicator flag bit, verifying whether the target section is physically populated in the address space.

  • Bit 1 (SECTION_HAS_MEM_MAP): Flags whether this specific memory section possesses a valid, initialized page descriptor array (mem_map), allowing the subsystem to fence off unmapped or invalid memory zones.

  • Bit 2 (SECTION_IS_ONLINE): Registers whether the memory block is currently online; this indicator is heavily processed during runtime memory hot-plug loops.

  • Bit 3 (SECTION_EARLY_INIT): Tracks whether the target section completed its initial provisioning during the early bootstrap lifecycle phase. This flag is critical for hot-unplug routines; if a section is attached to a hot-pluggable hardware component but its .early_init bit is asserted, the kernel prevents the structural destruction of its tracking metadata when the peripheral is removed.

  • Bit 4 and Above: Encodes the combined bit vectors storing the unique hardware NUMA node identification index paired with the absolute physical base page address.

The master structural layout of the struct mem_section descriptor is configured as follows:

struct mem_section {
	unsigned long section_mem_map;
	struct mem_section_usage *usage;
#ifdef CONFIG_PAGE_EXTENSION
	struct page_ext *page_ext;
	unsigned long pad;
#endif
}; 

When the compilation configuration enables the modern Virtual Memory Map optimization profile (CONFIG_SPARSEMEM_VMEMMAP), the framework can subdivide each parent memory section into an array of smaller, discrete sub-sections via the nested .usage attribute tracking block:

struct mem_section_usage {
#ifdef CONFIG_SPARSEMEM_VMEMMAP
	DECLARE_BITMAP(subsection_map, SUBSECTIONS_PER_SECTION);
#endif
	unsigned long pageblock_flags[0];
};

To coordinate lookups, Linux maintains a global two-dimensional array of type struct mem_section organized as mem_section[root][id]. The discrete indexing coordinates used to traverse this matrix are resolved by extracting the root boundary and the relative tracking index of the target section via the following arithmetic equations:

$$root = \lfloor nr/N\rfloor$$

$$id = nr - root \times N$$

Where N defines the constant threshold representing the absolute count of sections bundled beneath an individual root container, and nr represents the raw global section index.

When the system compilation parameters disable extreme sparse memory indexing (CONFIG_SPARSEMEM_EXTREME), this tracking grid collapses into a flat, statically allocated single-dimensional array composed of NR_MEM_SECTIONS elements (representing the absolute maximum section capacity supported by the platform configuration). Conversely, when SPARSEMEM_EXTREME is active, each distinct row within the multidimensional array is dynamically allocated from the early boot-stage memories to host exactly PAGE_SIZE (4,096) contiguous mem_section descriptor cells.

4. Device Memory Model (ZONE_DEVICE)

Device memory structures are architected over the foundational SPARSEMEM_VMEMMAP layout but remain completely separated from standard system-usable RAM pools. This specialized memory model is explicitly dedicated to managing persistent non-volatile memory or hardware page blocks hosted directly on external peripheral expansion buses that are dynamically discovered by third-party device drivers.

To maintain runtime isolation, these peripheral page blocks are strictly barred from being flagged as online within the global zone buddy allocators. During the page lifecycle and reference tracking phases, the kernel enforces a unified dependency tracking scheme; any subsystem executing a resource pin loop must simultaneously increment the reference counter of the specific memory page and update the reference constraints tracking the host peripheral device node itself.

8.2.15.8.2 The Technical Execution Process of Boot Memory Initialization

The early boot-stage memory initialization routine is defined as follows:

void __init bootmem_init(void)
{
	memblock_allow_resize();
	find_limits(&min_low_pfn, &max_low_pfn, &max_pfn);
	early_memtest((phys_addr_t)min_low_pfn << PAGE_SHIFT, (phys_addr_t)max_low_pfn << PAGE_SHIFT);
	sparse_init();
	zone_sizes_init(min_low_pfn, max_low_pfn, max_pfn);
}

The underlying subroutines and memory profiling loops operate according to the following design parameters:

  • The initial function memblock_allow_resize() asserts the global system configuration flag bit memblock_can_resize. This allows the early allocator to dynamically scale and shift its localized region array sizes to accommodate subsequent resource allocations.

  • The tracking routine find_limits() scans the active memblock databases to calculate the absolute physical Page Frame Numbers (PFNs) defining the baseline system limits. It resolves the page frame index matching the lowest available address (min_low_pfn), the index matching the highest theoretical low-memory address boundary (max_low_pfn), and the index registering the actual highest available physical address present on the platform (max_pfn).

  • The function early_memtest() executes an early hardware integrity verification loop. It sweeps across the physical memory channels extending from the absolute lowest usable address up to the highest available page block, injecting specialized bit-pattern data strings on a zone-by-zone basis to identify faulty or unstable RAM rows before the core kernel assumes full execution.

  • The framework utility sparse_init() initializes the multi-dimensional tracking matrices required by the Sparse Memory Model (SPARSEMEM). It allocates memory section descriptors, hooks root pointers, and executes the necessary setup stages to bring up the sparse paging grid.

  • The function zone_sizes_init() determines the exact starting Page Frame Numbers (PFNs) and physical linear sizes allocating the individual memory zones (ZONE_DMA, ZONE_NORMAL, ZONE_HIGHMEM, or ZONE_DEVICE). It dynamically allocates and provisions a dedicated struct zone tracker structure for each isolated zone. Within high-scale NUMA multiprocessor environments, it maps and cross-links these verified zone configurations onto their parent pg_data_t memory node descriptors.

8.2.15.8.3 Initialization of the Sparse Memory Model (sparse_init)

The sparse_init() function allocates physical memory memory arrays for the global mem_section multi-dimensional tracking grid and initializes its content. This initialization routine is defined within the core memory subsystem source module git/mm/sparse.c as follows:

void __init sparse_init(void)
{
	unsigned long pnum_end, pnum_begin, map_count = 1;
	int nid_begin;
	memblocks_present();    
	pnum_begin = first_present_section_nr();
	nid_begin = sparse_early_nid(__nr_to_section(pnum_begin));    
	set_pageblock_order();
	for_each_present_section_nr(pnum_begin + 1, pnum_end) {
		int nid = sparse_early_nid(__nr_to_section(pnum_end));    
		if (nid == nid_begin) {
			map_count++;
			continue;
		}
		sparse_init_nid(nid_begin, pnum_begin, pnum_end, map_count);
		nid_begin = nid;
		pnum_begin = pnum_end;
		map_count = 1;
	}
	sparse_init_nid(nid_begin, pnum_begin, pnum_end, map_count);
	vmemmap_populate_print_last();
}

The underlying subroutines and memory tracking iterations operate according to the following design parameters:

  • The tracking routine memblocks_present() loops across the platform memory maps to invoke memory_present(), which populates the initial sparse structural grid for all validated memory channels.

  • The function memory_present() first delegates execution down to sparse_index_init() to allocate the physical memory descriptors tracking the underlying mem_section tables. It temporarily packs the corresponding hardware NUMA node identification index into the structural .section_mem_map field of each section descriptor word for downstream consumption. Later in the execution path, once this node identification context has been processed, the downstream utility sparse_init_nid() permanently overwrites this specific field offset to hold the absolute physical tracking address of the section's actual page maps.

To accelerate physical node lookups, the memory management subsystem maintains a global lookup database array named section_to_node_table. This index table uses the raw memory section number as an evaluation key and returns the corresponding NUMA node identification index, enabling the kernel to resolve structural node affinity mapping profiles instantly. The memory_present() routine writes these values into the look-up table by calling set_section_nid(). The core implementation of memory_present() is structured as follows:

static void __init memory_present(int nid, unsigned long start, unsigned long end)
{
	unsigned long pfn;
	start &= PAGE_SECTION_MASK;
	mminit_validate_memmodel_limits(&start, &end);    
	for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION) {
		unsigned long section = pfn_to_section_nr(pfn);
		struct mem_section *ms;
		sparse_index_init(section, nid);     
		set_section_nid(section, nid);
		ms = __nr_to_section(section);    
		if (!ms->section_mem_map) {
			ms->section_mem_map = sparse_encode_early_nid(nid) 
 			| SECTION_IS_ONLINE;
			section_mark_present(ms);
		}
	}
}

It must be explicitly noted that although the for iteration loop tracking the execution of memory_present() advances its step pointer across absolute Page Frame Numbers, the lower-level memory allocation block managed by sparse_index_init() partitions space strictly at a Sparse Root tier granularity. If the initialization verification pass confirms that the system has already allocated a root tracking container housing the targeted section index, sparse_index_init() skips allocating a new layout block and returns with no operation.

Upon finalizing the initial layout allocations of the global mem_section arrays, the master sparse_init() routing loop invokes first_present_section_nr() to extract the logical index matching the absolute first section flagged as physically populated in the address space. The structural macro helper __nr_to_section(nr) resolves the physical base memory address of the specific mem_section descriptor matching that index. Following this, sparse_early_nid() interprets the target descriptor fields, reading the raw bit vectors embedded inside the .section_mem_map configuration word to decode and extract the early NUMA node identifier index.

The Linux kernel can allocate memory chunks at a granular page level or scale lookups to process contiguous page blocks. The system configuration variable pageblock_order establishes the definitive allocation granularity and bit-mask layout utilized by the page buddy allocators; the routine set_pageblock_order() executes on startup to calculate and program this structural parameter.

The function sparse_init_nid() handles the allocation of physical memory blocks across each independent NUMA node to accommodate the massive contiguous arrays of struct page page descriptors that track every individual page frame resident within those memory sections. After securing this tracking memory allocation, sparse_init_nid() extracts the virtual base pointer referencing the section's primary struct page array and encodes it directly into the high-order bits of the corresponding .section_mem_map configuration word (as illustrated in Figure 8-28). It then asserts the structural status bits SECTION_HAS_MEM_MAP and SECTION_IS_EARLY to permanently seal the section tracking state. The comprehensive multi-dimensional structure mapping out the sparse memory tracking model once these initialization passes conclude is visualized below:

Figure 8-29 Architectural Data Inter-links of the Sparse Memory Model Subsystem

Upon completing the descriptor configuration loops and finalizing the paging grids tracking the terminal memory section, the sparse_init() function completes its early initialization tasks.

8.2.16 Standard Resource Request

The Linux kernel categorizes visual displays, parallel ports, and other basic peripherals as standard devices. Before these devices can be driven by the system, their designated hardware memory ranges and I/O addresses must be registered using standard resource allocation handlers. The standard resource allocation function request_standard_resources() is defined within the architecture setup module git/arch/arm/kernel/setup.c as follows:

static void __init request_standard_resources(const struct machine_desc *mdesc)
{
	phys_addr_t start, end, res_end;
	struct resource *res;
	u64 i;
	kernel_code.start   = virt_to_phys(_text);
	kernel_code.end     = virt_to_phys(__init_begin - 1);
	kernel_data.start   = virt_to_phys(_sdata);
	kernel_data.end     = virt_to_phys(_end - 1);
	for_each_mem_range(i, &start, &end) {
		unsigned long boot_alias_start;
		res_end = end - 1;
		boot_alias_start = phys_to_idmap(start);
		if (arm_has_idmap_alias() && boot_alias_start != IDMAP_INVALID_ADDR) 
{
			res = memblock_alloc(sizeof(*res), SMP_CACHE_BYTES);
 			if (!res)
   				panic("%s: Failed to allocate %zu bytes\n", __func__, sizeof(*res));
			res->name = "System RAM (boot alias)";
			res->start = boot_alias_start;
			res->end = phys_to_idmap(res_end);
			res->flags = IORESOURCE_MEM | IORESOURCE_BUSY;
			request_resource(&iomem_resource, res);
		}
		res = memblock_alloc(sizeof(*res), SMP_CACHE_BYTES);
		if (!res)
 			panic("%s: Failed to allocate %zu bytes\n", __func__, sizeof(*res));
		res->name  = "System RAM";
		res->start = start;
		res->end = res_end;
		res->flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
		request_resource(&iomem_resource, res);
		if (kernel_code.start >= res->start && kernel_code.end <= res->end)
			request_resource(res, &kernel_code);
		if (kernel_data.start >= res->start && kernel_data.end <= res->end)
			request_resource(res, &kernel_data);
	}
	if (mdesc->video_start) {
		video_ram.start = mdesc->video_start;
		video_ram.end   = mdesc->video_end;
		request_resource(&iomem_resource, &video_ram);
	}
	if (mdesc->reserve_lp0)
		request_resource(&ioport_resource, &lp0);
	if (mdesc->reserve_lp1)
		request_resource(&ioport_resource, &lp1);
	if (mdesc->reserve_lp2)
		request_resource(&ioport_resource, &lp2);
}

The Linux kernel maps the memory footprint consumed by its own text segments and global data variables as system memory resources, which requires it to file explicit reservations to secure these areas. Prior to tracking these requests, it invokes virt_to_phys() to compute the physical addresses corresponding to the virtual symbols defining the kernel code and data segments.

To complete the registration, the routine utilizes the for_each_mem_range() loop to iterate across every usable memory block discovered by the early allocator. For each distinct region found, it claims a raw memory slice from the early boot allocator to store the tracking struct resource descriptor. These blocks are then integrated into the centralized global memory resource database iomem_resource as standard system RAM.

When the loop encounters a physical memory range that encompasses the kernel code or data segments, it files a child reservation request directly under that specific memory region's node. It marks these child segments as busy (IORESOURCE_BUSY) and sets their resource classification properties to track system memory.

Certain system architectures embed specialized, hardwired memory blocks dedicated exclusively to early boot staging. If the target silicon revision includes this early boot memory, the kernel automatically parses and registers these spaces as standard system RAM.

Additionally, because virtual frame buffers and graphic display chips are supported by almost all contemporary Linux configurations, the routine pulls the physical starting and terminating addresses of video memory from the active machine_desc board descriptor and files an allocation request under the global iomem_resource tree to secure the video RAM block.

Finally, if the underlying platform hardware incorporates support for legacy parallel printer ports (LP devices), the function logs these specific hardware parameters and registers the corresponding I/O port address boundaries directly under the root port-mapped resource tree ioport_resource.

8.2.17 Flattening the Device Tree into a Hierarchical Object Model (unflatten_device_tree)

As detailed in preceding chapters regarding the design architecture of device trees, a compiled Device Tree Blob (.dtb) payload resides in physical memory as a single, flattened linear data stream. This linear packaging layout is highly optimized for storage and bootloader transmission but is inherently inefficient for runtime peripheral tracking or device node traversal. Because the running Linux kernel must continuously query the device tree to bind drivers and resolve interrupt line parameters, it must reconstruct this flattened stream into a multi-dimensional, hierarchical object tree.

The setup_arch() master loop invokes unflatten_device_tree() to dynamically parse the text properties inside the memory-resident .dtb blob and transform them into a comprehensive tree-structured network of runtime device nodes. The unflatten_device_tree() handler is maintained within the driver core subsystem module git/drivers/of/fdt.c with the following implementation:

void __init unflatten_device_tree(void)
{
	__unflatten_device_tree(initial_boot_params, NULL, &of_root, 
	                        early_init_dt_alloc_memory_arch, false);
	of_alias_scan(early_init_dt_alloc_memory_arch);
	unittest_unflatten_overlay_base();
}

The underlying subroutines and parsing tasks operate according to the following design parameters:

  • The primary core routine __unflatten_device_tree() acts as the main translation engine, systematically unpacking the linearized initial_boot_params buffer to generate full programmatic runtime objects, anchoring the newly synthesized hierarchical node structure at the global root variable pointer of_root. The memory allocations required to host these node descriptors are dynamically drawn from early boot-stage pools via the callback handler early_init_dt_alloc_memory_arch.

  • The system utility of_alias_scan() executes a targeted sweep across the newly expanded hierarchy to interrogate the /chosen and /aliases container nodes. It extracts all structural hardware shorthand properties and device aliases found beneath these nodes and registers them into a global centralized array database, making them instantly available to accelerate device lookups downstream.

  • The validation utility unittest_unflatten_overlay_base() sweeps the system blocks to look up and parse any user-supplied partial device tree layers. This provides the kernel with flexible, modular hooks to inject custom hardware device overlays and dynamically alter or extend properties on the master device tree to suit specific localized engineering requirements.

8.2.17.1 Device Tree Conversion

The function responsible for converting a flattened device tree (FDT) into a tree-structured device tree is __unflatten_device_tree(). This function is defined in the file git/drivers/of/fdt.c and performs the tree structure conversion for all child nodes of the root node. Omitting debugging statements, the function definition is as follows:

void *__unflatten_device_tree(const void *blob, struct device_node *dad, struct device_node **mynodes, void *(*dt_alloc)(u64 size, u64 align), bool de-tached)
{
	int size;
	void *mem;
	if (!blob) {
		return NULL;
	}
	if (fdt_check_header(blob)) {
		return NULL;
	}
	size = unflatten_dt_nodes(blob, NULL, dad, NULL);
	if (size < 0)
		return NULL;
	size = ALIGN(size, 4);
	mem = dt_alloc(size + 4, __alignof__(struct device_node));
	if (!mem)
		return NULL;
	memset(mem, 0, size);
	*(__be32 *)(mem + size) = cpu_to_be32(0xdeadbeef);
	unflatten_dt_nodes(blob, mem, dad, mynodes);
	if (be32_to_cpup(mem + size) != 0xdeadbeef)
		be32_to_cpup(mem + size);
	if (detached && mynodes) {
		of_node_set_flag(*mynodes, OF_DETACHED);
	}
	return mem;
}

When unflatten_device_tree() invokes this function, blob points to the base memory address where the flattened DTB file resides, and its value is initial_boot_params. dad represents the parent node of the target node; since the conversion is performed on the entire device tree, the parent node is assigned NULL. dt_alloc points to the function used for memory allocation, which in this context utilizes the allocation function early_init_dt_alloc_memory_arch() to allocate memory. mynodes stores the address of of_root, which points to the root node of the device tree after hierarchical serialization. Each node in the hierarchical device tree is described by the device_node structure. The definition of device_node is as follows:

struct device_node {
	const char *name;
	phandle phandle;
	const char *full_name;
	struct fwnode_handle fwnode;
	struct    property *properties;
	struct    property *deadprops;    /* removed properties */
	struct    device_node *parent;
	struct    device_node *child;
	struct    device_node *sibling;
#if defined(CONFIG_OF_KOBJ)
	struct    kobject kobj;
#endif
	unsigned long _flags;
	void    *data;
};

The properties field forms a linked list used to describe all the attributes belonging to that node. The kobj field is a kernel object (kobject), which represents the fundamental building block of the system file system (sysfs). sysfs provides the user space with various types of information regarding the devices.

By leveraging the parent, child, and sibling pointers within the structure, the device tree can be organized into a hierarchical infrastructure.

__unflatten_device_tree() first invokes the function fdt_check_header() to validate the DTB file by checking its device tree magic number, header size, total file size, file version, structural block offset, and string block offset, thereby ensuring the legitimacy of the DTB file. The function __unflatten_device_tree() calls unflatten_dt_nodes() twice: the first pass scans the number of nodes, and the second pass executes the concrete conversion. The definition of unflatten_dt_nodes() is as follows:

static int unflatten_dt_nodes(const void *blob, void *mem, struct device_node *dad, struct de-vice_node **nodepp)
{
	struct device_node *root;
	int offset = 0, depth = 0, initial_depth = 0;
	struct device_node *nps[FDT_MAX_DEPTH];
	void *base = mem;
	bool dryrun = !base;
	if (nodepp)
		*nodepp = NULL;
	if (dad)
		depth = initial_depth = 1;
	root = dad;
	nps[depth] = dad;
	for (offset = 0; offset >= 0 && depth >= initial_depth; offset = fdt_next_node(blob, offset, &depth)) {
		if (WARN_ON_ONCE(depth >= FDT_MAX_DEPTH))
 			continue;
		if (!IS_ENABLED(CONFIG_OF_KOBJ) && !of_fdt_device_is_available(blob, offset)) 
			continue;
		if (!populate_node(blob, offset, &mem, nps[depth], &nps[depth+1], dryrun))
			return mem - base;
		if (!dryrun && nodepp && !*nodepp)
			*nodepp = nps[depth+1];
		if (!dryrun && !root)
			root = nps[depth+1];
	}
	if (offset < 0 && offset != -FDT_ERR_NOTFOUND) {
		pr_err("Error %d processing FDT\n", offset);
		return -EINVAL;
	}
	if (!dryrun)
		reverse_nodes(root);
	return mem - base;
}

During the initial invocation of unflatten_dt_nodes(), the value of mem is null, and consequently, the dryrun value evaluates to true. The unflatten_dt_nodes() function scans all child nodes within the blob and determines whether a node on the device tree is valid (i.e., nodes whose status property is set to "ok" or "okay") via the function of_fdt_device_is_available(). The purpose of the populate_node() function is to calculate the memory size required to convert all valid nodes on the device tree into a tree structure. This memory is designated to store the device_node structures, property structures, and node names of the supported nodes.

After determining the required memory size, the function __unflatten_device_tree() allocates memory according to the required size by invoking the function early_init_dt_alloc_memory_arch(). The actual allocated memory space is 4 bytes larger than the required size. After clearing the allocated memory to zero, the hexadecimal value 0xDEADBEEF is written into the extra 4 bytes allocated to mark the termination of the hierarchical device tree. The magic number 0xDEADBEEF is widely used to signify invalid or placeholder data.

Upon completing these preparatory tasks, __unflatten_device_tree() invokes unflatten_dt_nodes() for the second time. In this invocation, the previously allocated memory address and the address of of_root are passed to the unflatten_dt_nodes() function. Since the mem address is not null during this call, the dryrun value is false. This run executes the operations skipped during the first call, primarily assigning values to the various fields of the device_node structure. In addition to assigning values to fields related to the device tree such as phandle and properties, it also populates the three fields parent, child, and sibling, thereby establishing the hierarchical hierarchy of the device tree.

Because certain device drivers rely on the chronological ordering of nodes within the device tree, the sequence of the hierarchical device tree nodes is inverted by calling the function reverse_nodes() once the hierarchical device tree has been fully established.

The structural arrangement of the hierarchical device tree is shown below:

Figure 8-30 Hierarchical Device Tree\ In the figure above, the black blocks represent nodes, and the purple blocks represent node properties, wherein the child and sibling sub-nodes at the same level share the same parent node.

8.2.17.2 Scanning Alias Nodes

The device tree contains a node named /aliases and a node named /chosen. The sub-nodes under /aliases establish aliases for other nodes in the device tree, allowing the corresponding nodes to be accessed via these aliases. The /chosen node is used to pass parameters to the system during the boot process. To facilitate system utilization, unflatten_device_tree() invokes the function of_alias_scan() to scan all sub-nodes under the /aliases node as well as the parameters under /chosen. It then stores all the properties of these nodes in a global table for future use. The definition of the function of_alias_scan() is as follows:

void of_alias_scan(void * (*dt_alloc)(u64 size, u64 align))
{
	struct property *pp;
	of_aliases = of_find_node_by_path("/aliases"); 
	of_chosen = of_find_node_by_path("/chosen");
	if (of_chosen == NULL)
	of_chosen = of_find_node_by_path("/chosen@0");
	if (of_chosen) {
		const char *name = NULL;
		if (of_property_read_string(of_chosen, "stdout-path", &name))    
			of_property_read_string(of_chosen, "linux,stdout-path",&name);
		if (IS_ENABLED(CONFIG_PPC) && !name)
			of_property_read_string(of_aliases, "stdout", &name);
		if (name)
			of_stdout = of_find_node_opts_by_path(name, &of_stdout_options);    
	}
	if (!of_aliases)
		return;
	for_each_property_of_node(of_aliases, pp) {
		const char *start = pp->name;
		const char *end = start + strlen(start); 
		struct device_node *np;
		struct alias_prop *ap;
		int id, len;
		if (!strcmp(pp->name, "name") ||!strcmp(pp->name, "phandle") ||!strcmp(pp->name, 
    "linux,phandle"))
            		continue;
		np = of_find_node_by_path(pp->value);
		if (!np)
			continue;
		while (isdigit(*(end-1)) && end > start)
			end--;
		len = end - start;
		if (kstrtoint(end, 10, &id) < 0)
			continue;
		ap = dt_alloc(sizeof(*ap) + len + 1, __alignof__(*ap));
		if (!ap)
			continue;
		memset(ap, 0, sizeof(*ap) + len + 1);
		ap->alias = start;
		of_alias_add(ap, np, id, start, len);
	}
}

of_alias_scan() first invokes the function of_find_node_by_path("/aliases") to search for the pointer pointing to the /aliases node within the hierarchical device tree referenced by of_root, and assigns the returned pointer to the global variable of_aliases. It then invokes the function of_find_node_by_path("/chosen") to look up the pointer pointing to the /chosen node in the hierarchical device tree, and assigns the returned pointer value to the global variable of_chosen. Here, of_aliases and of_chosen are global pointers pointing to structures of type struct device_node.

In a DTB file, the /chosen node can also be defined via the alternative format /chosen@0. Therefore, if the aforementioned function call fails to locate the /chosen node, a subsequent lookup for the /chosen node is executed via a call to of_find_node_by_path("/chosen@0"). It should be noted here that functions prefixed with fdt_ are typically utilized when operating on a flattened device tree, whereas functions prefixed with of_ are adopted when interacting with a hierarchical device tree. Functions prefixed with of_ are defined within the source files located under the git/drivers/of subdirectory, whereas functions prefixed with fdt_ are defined within the source files located under the git/scripts/dtc/libfdt subdirectory.

After successfully locating the /chosen node, of_alias_scan() utilizes the function of_property_read_string() to find and read the stdout-path property from the node pointed to by of_chosen, which specifies the standard output device. If this property is not found, it subsequently looks up and reads the value of the linux,stdout-path property. If it is still not found and the system enables CONFIG_PPC, it will further look up and read the value of the stdout property from the /aliases node. After reading property values such as stdout-path, the corresponding stdout option values are extracted from the property value, an operation executed by the of_find_node_opts_by_path() function. Since the options might contain an alias of a node path, the node pointed to by of_aliases along with its child nodes must also be traversed during the retrieval of option values.

To facilitate querying operations, Linux establishes a linked list designated as aliases_lookup. The nodes of this linked list are defined by the alias_prop structure, whose definition is as follows:

struct alias_prop {
	struct list_head link;
	const char *alias;
	struct device_node *np;
	int id;
	char stem[];
};

The link field of the structure serves as the linked list node pointer to point to the preceding and succeeding nodes in the list. The alias field of the alias_prop structure points to a specific property name of an alias node, np points to the corresponding node within the hierarchical device tree mapped to the alias, id represents the numerical component trailing the property name of the alias, and stem represents the character component of the alias name.

The properties of the /aliases node comprise property names and their corresponding property values. The property name acts as the alias for a particular node, while the property value signifies the absolute path of the node corresponding to that alias. The of_alias_scan() function traverses all properties belonging to the of_aliases node. Since the property value of an alias node represents the absolute path of the node to which the alias corresponds, the node pointer of the target node mapped by the alias can be acquired by invoking the function of_find_node_by_path(pp->value) with the property value pp->value of the /aliases node property.

After retrieving the absolute path of the node, the numerical component of the alias name is converted into an id value, and memory is allocated to store a new alias_prop node. Subsequently, the pointer pointing to the alias name is assigned to the alias field of the alias_prop structure. Finally, the remaining fields of the structure are populated by invoking the function of_alias_add(), and the newly created alias_prop structure is inserted into the aliases_lookup linked list. The finalized topology of the linked list is illustrated in the figure below.

Figure 8-31 The aliases_lookup Linked List

8.2.17.3 Unflattening of the Device Tree Overlay Base

The device tree is utilized to support devices that the system cannot automatically discover, and it is typically supplied by operating system developers. In certain scenarios, users wish to provide fragments of their own device tree files, or substitute original device tree nodes provided by the operating system with their own partial device tree nodes. Device tree overlay capabilities provide the functionality to modify the master device tree (the device tree provided by the operating system). Users can leverage overlay nodes provided by their own device trees or include their own dts files via /include/ statements to modify the device tree after the master device tree has been imported into memory. Whether the system opts to support device tree overlays can be configured via the compilation configuration switch CONFIG_OF_UNITTEST.

After scanning the alias nodes, the device tree hierarchization function copies the device tree overlay base file—generated during compilation and situated between __dtb_overlay_base_begin and __dtb_overlay_base_end—into a buffer. It then invokes the __unflatten_device_tree() function once again to unflatten the base device tree within this buffer into a hierarchical topology, thereby generating the overlay base device tree. This tree is stored at the location specified by overlay_base_root to be utilized for device tree overlay functional unit testing during later stages of the boot process.

8.2.18 Hardware Configuration for Multi-Core CPUs

After unflattening the flattened device tree, the framework-based hardware configuration function setup_arch() begins to execute multi-core-related hardware settings. This primarily encompasses the configuration of the CPU logic map and the initialization of the Power State Coordination Interface (PSCI) device tree. If the system is a symmetric multiprocessing (SMP) system, the initialization of multi-core CPUs is also executed.

8.2.18.1 Initializing the CPU Logical Map

The primary task of initializing the CPU logical map is to retrieve the physical identification number (mpidr) of each individual CPU from the device tree, and subsequently construct a logical mapping array that represents the correspondence between the physical CPU IDs and their logical IDs. This array is named cpu_logical_map. For ARM systems, the encoding format of the mpidr is as follows:

Figure 8-32 ARM MPIDR Encoding Format

The first slot of the logical relationship array stores the physical ID of the boot CPU. Following that, based on the traversal sequence of the device tree, the physical IDs of all discovered CPU nodes are sequentially stored into the subsequent positions of this array. Consequently, the index of the array acts as the logical CPU ID, and the content of the index represents its corresponding physical CPU ID. The function that initializes the CPU logical map is defined within the file git/arch/arm/kernel/devtree.c, as shown below:

void __init arm_dt_init_cpu_maps(void)
{
	struct device_node *cpu, *cpus;
	int found_method = 0;
	u32 i, j, cpuidx = 1;
	u32 mpidr = is_smp() ? read_cpuid_mpidr() & MPIDR_HWID_BITMASK : 0;
	u32 tmp_map[NR_CPUS] = { [0 ... NR_CPUS-1] = MPIDR_INVALID };
	bool bootcpu_valid = false;
	cpus = of_find_node_by_path("/cpus");
	if (!cpus)
		return;
	for_each_of_cpu_node(cpu) {
		const __be32 *cell;
		int prop_bytes;
		u32 hwid;
		cell = of_get_property(cpu, "reg", &prop_bytes);
		if (!cell || prop_bytes < sizeof(*cell)) {
			pr_debug(" * %pOF missing reg property\n", cpu);
			of_node_put(cpu);
			return;
		}
		do {
			hwid = be32_to_cpu(*cell++);
			prop_bytes -= sizeof(*cell);
		} while (!hwid && prop_bytes > 0);
		if (prop_bytes || (hwid & ~MPIDR_HWID_BITMASK)) {
			of_node_put(cpu);
			return;
		}
		for (j = 0; j < cpuidx; j++)
			if (WARN(tmp_map[j] == hwid,
				 "Duplicate /cpu reg properties in the DT\n")) {
				of_node_put(cpu);
				return;
			}
		if (hwid == mpidr) {
			i = 0;
			bootcpu_valid = true;
		} else {
			i = cpuidx++;
		}
		if (WARN(cpuidx > nr_cpu_ids, "DT /cpu %u nodes greater than " "max cores %u, 
  			capping them\n", cpuidx, nr_cpu_ids)) {
			cpuidx = nr_cpu_ids;
			of_node_put(cpu);
			break;
		}
		tmp_map[i] = hwid;
		if (!found_method)
			found_method = set_smp_ops_by_method(cpu);
	}
	if (!found_method)
		set_smp_ops_by_method(cpus);
	if (!bootcpu_valid) {
		pr_warn("DT missing boot CPU MPIDR[23:0], fall back to default cpu_logical_map\n");
		return;
	}
	for (i = 0; i < cpuidx; i++) {
		set_cpu_possible(i, true);
		cpu_logical_map(i) = tmp_map[i];
	}
}

As established previously, once the device tree is unflattened, every node on the device tree is represented by a struct device_node structure. Thus, both the cpu and cpus pointers in the function point to struct device_node structures.

The function arm_dt_init_cpu_maps() first determines whether the system supports symmetric multiprocessing booting. The system provides two methods to configure SMP booting: one method is configured via the compilation switch CONFIG_SMP, and the other method is configured via the compilation switch CONFIG_SMP_ON_UP (Uniprocessor). The first method is suitable for hardware architectures that are natively symmetric multi-core systems, whereas the second method is geared toward single-core hardware systems that intend to execute an SMP-enabled operating system. If the system supports SMP booting, the mpidr (Multiprocessor Affinity Register) value is read from the cp15 c0 c5 register; if SMP booting is not supported, the mpidr is cleared to zero.

After reading the hardware mpidr value, the function obtains a pointer to the /cpus node by invoking of_find_node_by_path("/cpus"). Then, utilizing this pointer, it iterates through each individual CPU node enclosed within the /cpus node to read the value of the reg property of each CPU node, which represents the physical ID of that CPU node. Upon reading the physical ID of a CPU node, the function verifies whether the physical ID is valid. The retrieved property value is considered invalid if any of the following conditions are met:

  • The CPU node does not contain a reg property.

  • The number of bytes contained within the reg property value is less than 4.

  • The upper 8 bits of the reg property value do not equal 0.

  • The exact same property value appears in more than one (inclusive of two) CPU nodes.

After validating the legitimacy of the property value, if this property value matches the mpidr value read from the hardware, the CPU currently being traversed is identified as the boot CPU. Under this circumstance, the physical ID of this CPU node must be written into the first position of the logical relationship table. If it does not equal the value of mpidr, the physical ID values read from the device tree are written into the logical relationship table sequentially starting from the second position, following the traversal order of the CPU nodes.

During the traversal of the various CPUs, the function arm_dt_init_cpu_maps() also invokes set_smp_ops_by_method(). This allows developers to configure customized SMP CPU initialization routines for each CPU, which include functions such as smp_init_cpus(), smp_prepare_cpus(), smp_secondary_init(), smp_boot_secondary(), as well as hotplug-related operations like cpu_kill(), cpu_die(), cpu_can_disable(), and cpu_disable(). The system is notified to utilize its self-contained initialization routines by specifying the enable-method property within the CPU nodes of the device tree file.

Concurrently with the construction of the cpu_logical_map array, the function arm_dt_init_cpu_maps() also builds a bitmask _cpu_possible_mask for all discovered CPUs. That is, if the (id)-th CPU node exists in the device tree, the (id)-th bit of _cpu_possible_mask is set to 1; otherwise, it is cleared to 0.

8.2.18.2 PSCI Initialization

PSCI is the abbreviation for Power State Coordination Interface. New generation ARM architectures, such as ARMv8-A, provide a power management interface designed to interface directly with the operating system. Linux utilizes the structure:

struct psci_operations {
	u32 (*get_version)(void);
	int (*cpu_suspend)(u32 state, unsigned long entry_point);
	int (*cpu_off)(u32 state);
	int (*cpu_on)(unsigned long cpuid, unsigned long entry_point);
	int (*migrate)(unsigned long cpuid);
	int (*affinity_info)(unsigned long target_affinity, unsigned long lowest_affinity_level);
	int (*migrate_info_type)(void);
};

to define the interface between the operating system and the PSCI module. Device manufacturers can define their own PSCI operations according to the respective function signatures outlined within this structure, or provide Linux with the necessary information, thereby achieving compatibility support for Linux. Before the various functionalities provided by PSCI can be utilized, Linux must populate the supported fields within the psci_operations structure. The function that assigns values to the psci_operations structure is implemented in the file git/drivers/firmware/psci/psci.c, and the functions executing the diverse capabilities of PSCI are defined within the exact same file.

During the execution of architecture-based hardware initialization, setup_arch() invokes the function psci_dt_init() to traverse the hierarchical device tree to search for nodes possessing the "arm,psci-1.0" property. Nodes carrying this property natively support PSCI functionalities. The PSCI device driver supplied by the vendor provides the starting memory address of the init_fn() function via the data field of the of_device_id structure, which is leveraged to initialize the PSCI functional modules. By executing init_fn(), the function completes the corresponding initialization of the PSCI modules for all nodes that support PSCI capabilities. The definition of the psci_dt_init() function is as follows:

int __init psci_dt_init(void)
{
	struct device_node *np;
	const struct of_device_id *matched_np;
	psci_initcall_t init_fn;
	int ret;
	np = of_find_matching_node_and_match(NULL, psci_of_match, &matched_np);
	if (!np || !of_device_is_available(np))
		return -ENODEV;
	init_fn = (psci_initcall_t)matched_np->data;
	ret = init_fn(np);
	of_node_put(np);
	return ret;
}

The function of_find_matching_node_and_match() within this routine traverses the device tree starting from the root node to locate all nodes with properties matching "arm,psci-1.0". The of_device_is_available() function subsequently verifies whether the value of the status property of the matched node evaluates to "ok" or "okay". The init_fn function is supplied directly by the hardware manufacturer.

8.2.18.3 SMP CPU PSCI Function Initialization

If the system supports a symmetric multiprocessing (SMP) CPU boot mechanism, it must initialize both the SMP CPUs and the various functional modules required by the SMP PSCI capabilities. As explained in the previous section, the function addresses for the diverse PSCI functional modules are supplied by the psci_operations structure, whereas the function addresses for the modules required by SMP CPU booting are supplied by the structure:

struct smp_operations {
#ifdef CONFIG_SMP
	void (*smp_init_cpus)(void);
	void (*smp_prepare_cpus)(unsigned int max_cpus);
	void (*smp_secondary_init)(unsigned int cpu);
	int  (*smp_boot_secondary)(unsigned int cpu, struct task_struct *idle);
#ifdef CONFIG_HOTPLUG_CPU
	int  (*cpu_kill)(unsigned int cpu);
	void (*cpu_die)(unsigned int cpu);
	bool  (*cpu_can_disable)(unsigned int cpu);
	int  (*cpu_disable)(unsigned int cpu);
#endif
#endif
};

For systems supporting hotplugging, multi-core CPUs require additional capabilities such as cpu_kill(), cpu_die(), and cpu_disable().

To utilize the features provided by multi-core symmetric CPUs, Linux first needs to assign the addresses of these respective functions to the corresponding fields of smp_ops, a static variable of type struct smp_operations. Prior to configuring the SMP CPUs, the setup_arch() function checks whether the machine descriptor mdesc provides an SMP CPU initialization routine smp_init. If the machine descriptor provides an initialization routine, the system uses the functions supplied by the machine descriptor to configure the various fields of smp_ops. If it is not provided, the fields of smp_ops are configured via the function smp_set_ops() using the respective function addresses provided by either psci_smp_ops or mdesc->smp. If PSCI is online, priority is given to the function addresses of psci_smp_ops defined in git/arch/arm/kernel/psci_smp.c.

After assigning values to smp_ops, setup_arch() invokes the function smp_init_cpus(), which is defined as follows:

void __init smp_init_cpus(void)
{
	if (smp_ops.smp_init_cpus)
		smp_ops.smp_init_cpus();
}

This function invokes the platform-dependent smp_init_cpus() routine to initialize each individual CPU core. For the i.MX6 Solo processor, a machine descriptor named __mach_desc_IMX6Q is statically defined via the macro DT_MACHINE_START(), and its smp field is initialized with the address of the function imx_smp_init_cpus() (defined in git/arch/arm/mach-imx/mach-imx6q.c). That is to address that the system provides the SMP CPU initialization routine via mdesc. The finalized result of expanding the DT_MACHINE_START macro is as follows:

static const struct machine_desc __mach_desc_IMX6Q __used
__section(".init.arch.info") = {
	.nr = ~0U, /* Or the corresponding board ID, typically ~0U in Device Tree (DT) mode */
	.name	= "Freescale i.MX6 Quad/DualLite (Device Tree)",
	.l2c_aux_val 	= 0,
	.l2c_aux_mask	= ~0,
	.smp	= &imx_smp_ops, /* Pointer after macro expansion of smp_ops(imx_smp_ops) */
	.map_io		= imx6q_map_io,
	.init_irq	= imx6q_init_irq,
	.init_machine	= imx6q_init_machine,
	.init_late      = imx6q_init_late,
	.dt_compat	= imx6q_dt_compat,
};

The function imx_smp_init_cpus(), defined in git/arch/arm/mach-imx/platsmp.c, is implemented as follows:

static void __init imx_smp_init_cpus(void)
{
	unsigned long arch_type;
	int i, ncores;
	asm volatile(
		".align 4\n"
		"mrc p15, 0, %0, c0, c0, 0\n"
		: "=r" (arch_type)
	);
	/* MIDR[15:4] defines ARCH type */
	__mxc_arch_type = (arch_type >> 4) & 0xfff;
	if (arm_is_ca7()) {
		unsigned long val;
		/* CA7 core number, [25:24] of CP15 L2CTLR */
		asm volatile("mrc p15, 1, %0, c9, c0, 2" : "=r" (val));
		ncores = ((val >> 24) & 0x3) + 1;
	} else {
		ncores = scu_get_core_count(scu_base);
	}
	for (i = ncores; i < NR_CPUS; i++)
		set_cpu_possible(i, false);
}

Its primary operations include:

  • Reading the MIDR register of the CP15 coprocessor via the assembly instruction mrc to identify the processor architecture, where bits [15:4] define the CPU model.

  • Acquiring the CPU core count. If it is a Cortex-A7 (such as i.MX7D), it reads the L2CTLR register. If it is another architecture (such as i.MX6Q/DL, Cortex-A9), it retrieves the CPU core count by reading the SCU register.

  • Updating the kernel CPU bitmap cpu_possible_mask.

8.2.18.4 Initialization of the SMP MPIDR Hash Table

A hash table is a fundamental concept in data structures and is extensively applied in the computer domain. It is a technique capable of storing and querying large tables through a smaller set of keys, thereby optimizing memory utilization. When generating or querying a hash table, a hash function is first employed to map a key into an index value, which is then utilized to look up the data corresponding to that key.

In practical applications, because the range of potential keys is far larger than the actual size of the hash table, different keys may resolve to the exact same index value when computed by the hash function. This gives rise to a phenomenon known as a hash collision. Diverse methodologies exist to resolve this issue, such as utilizing a linked list to store all keys and their corresponding values mapped to the same index; when a collision occurs, the target data is retrieved by traversing this linked list with the specific key.

Linux employs a hash table designated as mpidr_hash. This hash table stores the CPU states prior to entering sleep, which is leveraged by the system when entering low-power sleep states or during system wakeup. The purpose of the macro MPIDR_LEVEL_BITS is to initialize several fundamental parameters of this hash table.

As established from previous descriptions, the ARM mpidr encoding scheme is divided into three segments: aff0, aff1, and aff2. The rationale behind this tripartite division is to facilitate thread scheduling by choosing CPUs based on varying affinity preferences. One can define aff0 as the thread ID, aff1 as the CPU ID, and aff2 as the cluster ID; alternatively, aff0 can be defined as the CPU ID, aff1 as the cluster ID, and aff2 can be cleared to zero. Linux adopts the first configuration. During process scheduling, matching the configuration of aff0, aff1, and aff2 allows the system to set the priority level for a process when selecting a CPU core, such as binding a specific process to a designated core.

Linux leverages the value of mpidr as the key to generate and query this hash table. The index value is generated by a hash function named compute_mpidr_hash through bitwise shifting and OR operations on the mpidr values of the respective CPUs. This hash function is defined as a macro written in assembly language within the file git/arch/arm/kernel/sleep.S. The inputs to this function are rs0, rs1, rs2, along with aff0, aff1, and aff2, where rs0, rs1, and rs2 represent the right-shift bit counts for aff0, aff1, and aff2 respectively, while aff0, aff1, and aff2 are the values of the individual segments of the CPU mpidr. The functionality implemented by this macro is:

$$index = aff0 > > rs0|aff1 > > rs1|aff2 > > rs2$$

It should be pointed out here that utilizing this specific hash function guarantees that no collision phenomena will occur, even though the hash table generated via this approach is not the absolute minimal hash table possible.

When initializing the hash table, rs0, rs1, and rs2 are configured by the function smp_build_mpidr_hash() based on the mpidr values of all available CPUs. The definition of the smp_build_mpidr_hash() function is as follows:

static void __init smp_build_mpidr_hash(void)
{
	u32 i, affinity;
	u32 fs[3], bits[3], ls, mask = 0;
	for_each_possible_cpu(i)									
		mask |= (cpu_logical_map(i) ^ cpu_logical_map(0));
	for (i = 0; i < 3; i++) {
		affinity = MPIDR_AFFINITY_LEVEL(mask, i);
		ls = fls(affinity);
		fs[i] = affinity ? ffs(affinity) - 1 : 0;
		bits[i] = ls - fs[i];
	}
	mpidr_hash.shift_aff[0] = fs[0];
	mpidr_hash.shift_aff[1] = MPIDR_LEVEL_BITS + fs[1] - bits[0];
	mpidr_hash.shift_aff[2] = 2*MPIDR_LEVEL_BITS + fs[2] - (bits[1] + bits[0]);
	mpidr_hash.mask = mask;
	mpidr_hash.bits = bits[2] + bits[1] + bits[0];
	if (mpidr_hash_size() > 4 * num_possible_cpus())
		pr_warn("Large number of MPIDR hash buckets detected\n");
	sync_cache_w(&mpidr_hash);
}

This function first iterates through each available CPU. By executing a bitwise XOR operation against the mpidr of the boot CPU, it identifies all bits that flip across the mpidr registers of the diverse CPUs, and stores the intermediate result into the variable mask. It then combines the results of all CPUs together via bitwise OR operations. Consequently, a bit with a value of 1 within mask denotes that this specific bit has flipped in at least one CPU—meaning the value of this bit does not match the value of the corresponding bit in the boot CPU mpidr. The finalized mask value is utilized to determine the bitmask for index generation.

Since a bit with a value of 0 within mask indicates that the value of this bit in the mpidr remains unchanged across all CPUs, it can be inferred that this bit contributes nothing to the generation of the hash table index. By leveraging such a bitmask, the hash function can isolate the index generation from the influence of non-flipped bits, thereby reducing the memory footprint of the hash table.

To ensure that the LSB (Least Significant Bit) positions of aff0, aff1, and aff2 all align to bit 0, once the positions of the flipped bits across all CPU mpidr registers are determined, the macro definition MPIDR_AFFINITY_LEVEL(mask, i) shifts the LSB positions corresponding to each individual segment of aff0, aff1, and aff2 within the mask down to bit 0.

Through right-shifting, Linux discards the contiguous trailing zero segments starting from the LSB. The purpose of this operation is to further shorten the length of the keys used during lookups, thereby decreasing the storage space occupied by the hash table. The shift bit counts to be discarded for aff0, aff1, and aff2 are stored respectively in the shift_aff[0], shift_aff[1], and shift_aff[2] arrays of the mpidr_hash structure, whereas the total count of flipped bits is stored in the bits field of mpidr_hash. The mask bitmask required for calculating the index value is stored in the mask field of mpidr_hash.

When establishing the right-shift bit counts necessary for calculating the hash table index, the used variable fs[0] represents the position of the first flipped bit in aff0, fs[1] represents the position of the first flipped bit in aff1, and fs[2] represents the position of the first flipped bit in aff2. Due to the hardware encoding format of the ARM mpidr, fs[1] and fs[2] must be additionally shifted by MPIDR_LEVEL_BITS and 2 * MPIDR_LEVEL_BITS bits respectively, where the value of MPIDR_LEVEL_BITS evaluates to 8.

8.2.19 HYP Mode Check

As is established, ARM architecture CPUs possess multiple modes to provide users with varying levels of hardware access privileges. The primary CPU operating modes include User mode, System mode, Supervisor mode, Abort mode, FIQ mode, IRQ mode, Hypervisor mode (HYP mode), and Monitor mode. In terms of security partitioning, the CPU can operate in either a Secure state or a Non-secure state. When the CPU operates in the Non-secure state, it features three privilege levels: PL0, PL1, and PL2, wherein only Hypervisor mode possesses the PL2 privilege level. When the CPU operates in the Secure state, it features two privilege levels: PL0 and PL1. Hypervisor mode and Secure mode depend on hardware extensions. When the CPU is equipped with Virtualization hardware extensions, the system supports Hypervisor mode, whereas when the CPU is equipped with Security hardware extensions, the system supports Secure mode.

During the boot phase, the CPU typically operates in Supervisor mode or Hypervisor mode. If the system is an asymmetric multi-core system, the setup_arch() function invokes the Hypervisor check function hyp_mode_check() to verify whether the boot mode configuration is logical. This function is exclusively utilized for CPUs with Virtualization hardware extensions and is defined within the file git/arch/arm/kernel/setup.c. The function definition is as follows:

void __init hyp_mode_check(void)
{
#ifdef CONFIG_ARM_VIRT_EXT
	sync_boot_mode();
	if (is_hyp_mode_available()) {
		pr_info("CPU: All CPU(s) started in HYP mode.\n");
		pr_info("CPU: Virtualization extensions available.\n");
	} else if (is_hyp_mode_mismatched()) {
		pr_warn("started in wrong/inconsistent modes (primary CPU mode 0x%x)\n",
		__boot_cpu_mode & MODE_MASK);
		pr_warn("CPU: This may indicate a broken bootloader or firmware.\n");
	} else
		pr_info("CPU: All CPU(s) started in SVC mode.\n");
#endif
}

The function hyp_mode_check() acquires the boot mode by reading the value of the variable __boot_cpu_mode, wherein the function sync_boot_mode() flushes the cache prior to reading the value of the variable __boot_cpu_mode. The function is_hyp_mode_available() checks whether the mode portion of __boot_cpu_mode evaluates to HYP_MODE, whereas the function is_hyp_mode_mismatched() verifies whether the primary CPU mode is HYP mode while the remaining respective CPUs are configured to the exact same mode (all CPUs must be configured to identical modes). By checking the values of these two components, the system determines whether the HYP mode configuration is appropriate. The value of __boot_cpu_mode is populated during the U-Boot phase by the function __hyp_stub_install via the function store_primary_cpu_mode. These two functions are defined within the file git/linux/arch/arm/kernel/hyp-stub.S. As established in section 8.1.12, the __hyp_stub_install() function is invoked within the head.S file.

8.2.20 Reserving Memory for Kernel Crash Dump Information

Linux provides kernel crash data capturing and service tools such as kdump and kexec. When a kernel crash occurs, the capturing tool collects diagnostics data and generates a core dump file. Production-grade Linux distributions generally include these utilities; if omitted from the release artifacts, users can download and install them manually using package management tools.

Before starting the kdump or kexec services, a dedicated chunk of memory must be reserved for them. The required memory capacity can be configured via the cmdline string within the /chosen/bootargs node of the device tree file in the U-Boot source, or inside other corresponding configuration files. There are three formats for configuring the memory required by the capturing utility via cmdline: crashkernel = size,[high|low], crashkernel = size[@offset], and crashkernel = ramsize-range:size[,...][@offset]. Examples include crashkernel=192M,high, crashkernel=192M@16M, and crashkernel=512M-2G:64M,2G-:128M.

The routine responsible for parsing and configuring the kdump command is implemented as follows:

static void __init reserve_crashkernel(void)
{
	unsigned long long crash_size, crash_base;
	unsigned long long total_mem;
	int ret;

	total_mem = get_total_mem();
	ret = parse_crashkernel(boot_command_line, total_mem, &crash_size, &crash_base);
	if (ret)
		return;
	if (crash_base <= 0) {
		unsigned long long crash_max = idmap_to_phys((u32)~0);
		unsigned long long lowmem_max = __pa(high_memory - 1) + 1;
		if (crash_max > lowmem_max)
			crash_max = lowmem_max;
		crash_base = memblock_find_in_range(CRASH_ALIGN, crash_max, crash_size,  
 CRASH_ALIGN);
		if (!crash_base) {
			pr_err("crashkernel reservation failed - No suitable area found.\n");
			return;
		}
	} else {
		unsigned long long start;
		start = memblock_find_in_range(crash_base, crash_base + crash_size, crash_size, 
       SECTION_SIZE);
		if (start != crash_base) {
			pr_err("crashkernel reservation failed - memory is in use.\n");
			return;
		}
	}
	ret = memblock_reserve(crash_base, crash_size);
	if (ret < 0) {
		pr_warn("crashkernel reservation failed - memory is in use (0x%lx)\n",
(unsigned long)crash_base);
		return;
	}
	crashk_res.start = crash_base;
	crashk_res.end = crash_base + crash_size - 1;
	insert_resource(&iomem_resource, &crashk_res);
	if (arm_has_idmap_alias()) {
		static struct resource crashk_boot_res = {
			.name = "Crash kernel (boot alias)",
			.flags = IORESOURCE_BUSY | IORESOURCE_MEM,
		};
		crashk_boot_res.start = phys_to_idmap(crash_base);
		crashk_boot_res.end = crashk_boot_res.start + crash_size - 1;
		insert_resource(&iomem_resource, &crashk_boot_res);
	}
}

The function parse_crashkernel() within this procedure scans boot_command_line to detect whether it contains the "crashkernel" substring. If the "crashkernel" substring is present, it parses "crashkernel=" and its trailing parameters according to the three predefined formats described above to establish the designated memory size and address offset. The evaluated memory magnitude and offset address are then returned via crash_size and crash_base. total_mem denotes the aggregate memory dimension available for kdump operations.

Upon receiving the evaluated values of crash_size and crash_base, reserve_crashkernel() passes distinct sets of parameters to the function memblock_find_in_range() based on whether crash_base evaluates to zero, thereby selecting an appropriate block within the available memory pool. It subsequently reserves this memory block for kdump by calling the function memblock_reserve(), and registers the reserved block into the iomem_resource subsystem.

Certain ARM systems incorporate specialized hardware extensions intended for identity mapping (ID mapping). When the system features such ID mapping hardware extensions, it must export this specific information to utilities like kexec via the crashk_boot_res structure.

8.2.21 Machine Descriptor-Based Initialization

Upon completing the majority of the architecture-based hardware configurations, if the machine descriptor provides a generic interrupt service routine, a VGA console driver, or an early initialization routine, the architecture-based hardware subsystem will execute these initialization routines or assign their entry memory addresses to the corresponding variables.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com